This question already has answers here:
How do I wrap a string in a file in Python?
(4 answers)
Closed 9 months ago.
TLDR: How to create in Python a file object (preferably a io.TextIOWrapper, but anything with a readline() and a close() method would probably do) from a string ? I would like something like
f = textiowrapper_from_string("Hello\n")
s = f.readline()
f.close()
print(s)
to return "Hello".
Motivation: I have to modify an existing Python program as follows: the program stores a list (used as a stack) of file objects (more precisely, io.TextIOWrapper's) that it can "pop" from and then read line-by-line:
f = files[-1]
line = f.readline()
...
files.pop().close()
The change I need to do is that sometimes, I need to push into the stack a string, and I want to be able to keep the other parts of the program unchanged, that is, I would like to add a line like:
files.append(textiowrapper_from_string("Hello\n"))
Or maybe there is another method, allowing minimal changes on the existing program ?
There's io.StringIO:
from io import StringIO
files.append(StringIO("Hello\n"))
This question already has answers here:
How do you read a file into a list in Python? [duplicate]
(8 answers)
Closed 3 years ago.
What i am trying to do is read from a file, and insert the content from a file into a list in python 3. the file should look like this:
♥A
♣A
♥Q
♠Q
and the result i am expecting when i read from the file is that when i print the specific list is that it shows up like this
['♥A', '♣A', '♥Q', '♠Q']
How would i go about solving this?
And i have tried multiple solutions for this, like using for loops, but i dont understand how to do this
You can use the open function.
f = open("file.txt", "r")
l = list()
for line in f:
l.append(line)
f.close()
print(l)
This question already has answers here:
iterating over file object in Python does not work, but readlines() does but is inefficient
(3 answers)
Closed 3 years ago.
I was doing an exercise with the help of tutorial of python, trying to combine the codes used to read contents of file line by line and to make a list of lines from a file. The output I expected is that the text will be printed 2 times, which doesn’t work.
My operating system is Windows 10.
I use sublime text 3.
with open(filename) as f:
for line in f:
print(line)
lines = f.readlines()
for line in lines:
print(line.strip())
Output:
In Python you can use list.
In Python you can use class.
In Python you can use dictionary.
[Finished in 0.1s]
Why doesn’t print(line.strip()) work?
The reason is f is a file iterator which is completely exhausted after the loop (it is one-time consumable). There is nothing in f to read from and hence f.readlines() returns an empty list.
In fact, if you want to iterate over file lines over again, you should use f.readlines() to store list and iterate over that list any number of times.
This question already has answers here:
Correct way to write line to file?
(17 answers)
Closed 5 years ago.
My code is like this .
inputfile=np.genfromtxt('test1.dat')
for data in inputfile:
lat=floor(data)+(floor(abs((data-floor(data))*100))/60)+....
print lat
In command window I can see
12.9579738889
12.9579736111
12.9579727778
12.9579719444
12.9579711111
12.9579702778
12.9579694444
.......
But I want to save it in a text file in my working directory .
I am not getting how to proceed. All attempts failed.
Please give suggestions.
Thanks in advance.
It's really simple. Use open to open the file (get a file object which encapsulates the file descriptor) and then simply write to that file. In a true Pythonic way you'll want to use a context manager (with open(..) as file), so the the file is closed automatically when out of context.
inputfile=np.genfromtxt('test1.dat')
with open("/path/to/output.file", "w") as f:
for data in inputfile:
lat=floor(data)+(floor(abs((data-floor(data))*100))/60)+....
f.write("%f\n" % lat)
You can do following. I used f-string to format output, which is available in Python >= 3.6, but you can you any version to do some calculation first and then output the value.
>>> with open('test1.dat') as f_in:
... with open('outputfile.txt', 'w') as f_out:
... for data in f_in:
... f_out.write(f"{floor(data)+(floor(abs((data-floor(data))*100))/60)}\n")
if your data has more than one values you can use split function:
lan, lot = (float(x) for x in data.split(' '))
where ' ' is your separator between those values
This question already has answers here:
Reading a list of lists from a file as list of lists in python
(4 answers)
Closed 7 years ago.
My txt file looks like this:
[[1,3,5],[1,4,4]]
[[1,4,7],[1,4,8],[2,4,5]]
And I was trying to convert it into a list, which include all the lists in the txt file. So the desired output for my example would be:
[[[1,3,5],[1,4,4]], [[1,4,7],[1,4,8],[2,4,5]]]
It seems like an easy task, except that I could only get this:
['[[1,3,5],[1,4,4]]', '[[1,4,7],[1,4,8],[2,4,5]]']
Is there an easy way to convert the string type into a list?
The code I used :
input_list = []
with open("./the_file.txt", 'r') as f:
lines = f.read().split('\n')
for each_line in lines:
input_list.append(each_line)
f.close()
You really want to evaluate each line in your file as actual python code. However, doing so can be problematic (e.g.: what happens if one line says import os; os.system('rm -rf /')).
So you don't want to use something like eval for this
Instead, you might consider using ast.literal_eval, which has a few safeguards against this sort of behavior:
with open("./the_file.txt", 'r') as f:
answer = [ast.literal_eval(line.strip()) for line in f]
This can be done in one line with ast.literal_eval and a list comprehension:
from ast import literal_eval
input_list = [literal_eval(line) for line in open("./the_file.txt", 'r') ]
If your lines in the text file are well formatted, you can use eval.
input_list.append(eval(each_line))