Writing a list to a file and reading it back - python-3.x

I am a beginner and I have searched for my answer in this forum, and have tried to follow examples (many are more complex than I can understand at this point). I want to write my list, Variables, to a file and read it back when necessary.
a = 'M'
b = 456.78
c = 100
Variables = [a, b, c]
f = open("test5.txt", "w")
with open("test5.txt", "r") as opened_file:
for variable in Variables:
"test5.txt".write(variable, '\n')
I get a "AttributeError" 'str' object has no attribute 'write'
What do I change?
How would i read it back?

The error means you can't write to a string, instead you want to write to the opened file. Change the string test5.txt to the file you've opened f:
for variable in Variables:
f.write("%s\n" % variable)
f.close()
then read it back:
with open("test5.txt", "r") as opened_file:
variables = opened_file.readlines()
print(variables) #will print the file contents
Edit: as discussed in the comments, the original request to re-assign the values to the appropriate variable names is not possible, the next best option would be to assign each value read from the file to their indices in the original list. Unfortunately the original datatypes are lost, keeping only the string value.
for i in range(len(variables)):
Variables[i] = variables[i].strip()
print(Variables) # ['M', '456.78', '100']

Related

Printing an entire list, instead of one line

I am having trouble writing the entire list into an outfile. Here is the code:
with open(infline, "r") as f:
lines = f.readlines()
for l in lines:
if "ATOM" in l :
split = l.split()
if split[-1] == "1":
print(split)
#print(type(split))
with open( newFile,"w") as f:
f.write("Model Number One" + "\n")
f.write(str(split))
When I use print(split) it allows me to see the entire list (image below):
with open(infile, "r") as f:
lines = f.readlines()
for l in lines:
if "ATOM" in l :
split = l.split()
if split[-1] == "1":
#print(split)
print(type(split))
with open( newFile,"w") as f:
f.write("Model Number One" + "\n")
for i in range(len(split)):
f.write(str(split))
However, when I try to use f.write(split) I get an error because the function can only take a str not a list. So, I used f.write(str(split)) and it worked. The only issue now is that it only writes the last item in the list, not the whole list.
The function print is slightly more permissible than the method f.write, in the sense that it can accept lists and various types of objects as input. f.write is usually called by passing pre-formatted strings, as you noticed.
I think the issue with the code is that the write routine is nested inside the code. This causes Python to erase any contents stored inside newFile, and write only the last line read (l).
The problem can be easily fixed by changing the open call to open( newFile,"a"). The flag "a" tells Python to append the new contents to the existing file newFile (without erasing information). If newFile does not exist yet, Python will automatically create it.

How to read many files have a specific format in python

I am a little bit confused in how to read all lines in many files where the file names have format from "datalog.txt.98" to "datalog.txt.120".
This is my code:
import json
file = "datalog.txt."
i = 97
for line in file:
i+=1
f = open (line + str (i),'r')
for row in f:
print (row)
Here, you will find an example of one line in one of those files:
I need really to your help
I suggest using a loop for opening multiple files with different formats.
To better understand this project I would recommend researching the following topics
for loops,
String manipulation,
Opening a file and reading its content,
List manipulation,
String parsing.
This is one of my favourite beginner guides.
To set the parameters of the integers at the end of the file name I would look into python for loops.
I think this is what you are trying to do
# create a list to store all your file content
files_content = []
# the prefix is of type string
filename_prefix = "datalog.txt."
# loop from 0 to 13
for i in range(0,14):
# make the filename variable with the prefix and
# the integer i which you need to convert to a string type
filename = filename_prefix + str(i)
# open the file read all the lines to a variable
with open(filename) as f:
content = f.readlines()
# append the file content to the files_content list
files_content.append(content)
To get rid of white space from file parsing add the missing line
content = [x.strip() for x in content]
files_content.append(content)
Here's an example of printing out files_content
for file in files_content:
print(file)

How to print more variables into file?

I know how to print one value of variable but I have a problem with more variables into one line.
file = open("values","w+")
file.write(str(q+q_krok+omega+omega_krok+e+e_krok))
The desired files values:
1-8-9-9-6-6
I would like to print values of 6 variables into file and between them put some value, for instance -. Thank you
Put the values into a string, then simply write that string to file.
values = <whatever your values are, as a string>
with open(“values.txt”, “w”) as f:
f.write(values)
If you have a list of values, you could create the string by using a join statement.
val_list = [1, 2, 3, 4, 5]
values = '-'.join(val_list)
If you have a specific set of values stored in different vars, you could use an f-string.
values = f'{val1}-{val2}-{val3}-{val4}'
Try doing it this way:
li = [q,q_krok,omega,omega_krok,e,e_krok]
values = '-'.join(li)
with open("values_file", "w") as f:
f.write(values)
You can even do it this way:
file = open("values_file","w+")
file.write(values)
You can have the values into a list, like:
items = [1,8,9,9,6,6]
with open('test.txt, 'r') as f:
for elem in items[:-1]: -- for each element instead of last
print(elem, end="-") -- print the value and the separator
if (len(items) > 1):
print(items[-1]) -- print last item without separator
A very well-made tutorial about reading/writing to files in python can be watched here:
https://www.youtube.com/watch?v=Uh2ebFW8OYM&t=1264s

Reading file and getting values from a file. It shows only first one and others are empty

I am reading a file by using a with open in python and then do all other operation in the with a loop. While calling the function, I can print only the first operation inside the loop, while others are empty. I can do this by using another approach such as readlines, but I did not find why this does not work. I thought the reason might be closing the file, but with open take care of it. Could anyone please suggest me what's wrong
def read_datafile(filename):
with open(filename, 'r') as f:
a = [lines.split("\n")[0] for number, lines in enumerate(f) if number ==2]
b = [lines.split("\n")[0] for number, lines in enumerate(f) if number ==3]
c = [lines.split("\n")[0] for number, lines in enumerate(f) if number ==2]
return a, b, c
read_datafile('data_file_name')
I only get values for a and all others are empty. When 'a' is commented​, I get value for b and others are empty.
Updates
The file looks like this:
-0.6908270760153553 -0.4493128078936575 0.5090918714784820
0.6908270760153551 -0.2172871921063448 0.5090918714784820
-0.0000000000000000 0.6666999999999987 0.4597549674638203
0.3097856229862140 -0.1259623621214220 0.5475896447896115
0.6902143770137859 0.4593623621214192 0.5475896447896115
The construct
with open(filename) as handle:
a = [line for line in handle if condition]
b = [line for line in handle]
will always return an empty b because the iterator in a already consumed all the data from the open filehandle. Once you reach the end of a stream, additional attempts to read anything will simply return nothing.
If the input is seekable, you can rewind it and read all the same lines again; or you can close it (explicitly, or implicitly by leaving the with block) and open it again - but a much more efficient solution is to read it just once, and pick the lines you actually want from memory. Remember that reading a byte off a disk can easily take several orders of magnitude more time than reading a byte from memory. And keep in mind that the data you read could come from a source which is not seekable, such as standard output from another process, or a client on the other side of a network connection.
def read_datafile(filename):
with open(filename, 'r') as f:
lines = [line for line in f]
a = lines[2]
b = lines[3]
c = lines[2]
return a, b, c
If the file could be too large to fit into memory at once, you end up with a different set of problems. Perhaps in this scenario, where you only seem to want a few lines from the beginning, only read that many lines into memory in the first place.
What exactly are you trying to do with this script? The lines variable here may not contain what you want: it will contain a single line because the file gets enumerated by lines.

Python file i/0: error -- How to write to a file when the filename given is a string?

I have a function that accepts d (dictionary that must be sorted asciibetically by key,) and filename (file that may or may not exist.) I have to have exact format written to this file and the function must return None.
Format:
Every key-value pair of the dictionary should be output as: a string that starts with key, followed by ":", a tab, then the integers from the value list. Every integer should be followed by a "," and a tab except for the very last one, which should be followed by a newline.
The issue is when I go to close the file and run my testers, it tells me this error:
'str' object has no attribute 'close'
Obviously that means my file isn't a file, it's a string. How do I fix this?
Here is my current functions that work together to accept the dictionary, sort the dictionary, open/create file for writing, write the dictionary to the file in specified format that can be read as a string, and then close the file:
def format_item(key,value):
return key+ ":\t"+",\t".join(str(x) for x in value)
def format_dict(d):
return sorted(format_item(key,value) for key, value in d.items())
def store(d,filename):
with open(filename, 'w') as f:
f.write("\n".join(format(dict(d))))
filename.close()
return None
Example of expected output:
IN: d = {'orange':[1,3],'apple':[2]}"
OUT: store(d,"out.txt")
the file contents should be read as this string: "apple:\t2\norange:\t1,\t3\n"
You have actually set the file handle to f but you are trying to close filename.
so your close command should be f.close()

Resources