This question already has answers here:
Using "readlines()" twice in a row [duplicate]
(3 answers)
Why can't I call read() twice on an open file?
(7 answers)
Closed 7 years ago.
I have a quick question about the readlines() method for file objects in Python.
I have a file (file1.txt) containing the following:
one
two
three
four
five
I know I can use readlines() on this file in the interpreter like so:
>>>f = open('file1.txt', 'r+')
>>>f.readlines()
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
Similarly, I can do this:
>>>f = open('file1.txt', 'r+')
>>>lines = f.readlines()
>>>lines
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
However, it seems like I can only run the readlines() method once:
>>>f = open('file1.txt', 'r+')
>>>f.readlines()
['one\n', 'two\n', 'three\n', 'four\n', 'five\n']
>>>lines = f.readlines()
>>>lines
[]
What is going on here? Why does f.readlines() return an empty list the second time I call it?
Thanks.
When you read the file once, the file pointer have moved to the end of the file, you have to call f.seek(0) to move the file pointer back to the start.
Related
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:
Why can't I call read() twice on an open file?
(7 answers)
Closed 5 years ago.
Why does following code1 works and code2 doesn't?
Code1:
#Read from a file
readMe = open('WriteToFile.txt', 'r').read()
print( readMe)
splitMe = readMe.split('\n')
print(splitMe)
Code 2:
#Read from a file
readMe = open('WriteToFile.txt', 'r')
print( readMe.read())
splitMe = readMe.read().split('\n')
print(splitMe)
I am getting the following output for code2:
while I want the output to be like code1 :
Once you call read() to go through a file, the file "pointer" (kinda like cursor) stays at the end of the file, and calling read() again does nothing since you're already at the end (and there's nothing to read). You need to move the pointer to the beginning of the file with file.seek(0).
However, it's better to just read it once to a string and use that:
readMe = open('WriteToFile.txt', 'r')
content = readMe.read()
print( content)
splitMe = content.split('\n')
print(splitMe)
Even better is to use the with statement, which automatically closes the file for you:
with open('WriteToFile.txt', 'r') as file:
content = file.read()
print(content)
lines = content.split('\n')
print(lines)
Although, if your end goal is to just get the lines, you can use readlines():
with open('WriteToFile.txt', 'r') as file:
lines = file.readlines()
print(lines)
This question already has answers here:
Attempting to read open file a second time gets no data
(4 answers)
Using "readlines()" twice in a row [duplicate]
(3 answers)
Closed 4 years ago.
I was trying to learn and experiment with Python today, and I got into trying to open a text file, reading the lines from it, and then writing those lines in a 2nd text file. After that, I tried to load the lines from both files into lists, and print those lists in the console. Here is the experimental code:
f = open('D:\\origFile.txt', 'r')
f2 = open('D:\\copyFile.txt', 'w')
for line in f:
f2.write(line.rstrip() + ' ')
f2.close()
s=""
for linez in f:
s += linez
print (s)
s2=""
f2 = open('D:\\copyFile.txt', 'r+')
reading = f2.readlines()
print (reading)
for linex in f2:
s2 += linex
print (linex)
list1=s.split()
list2=s2.split()
print(list1)
print(list2)
f.close()
f2.close()
The code works as expected only when I remove or comment this part:
f2 = open('D:\\copyFile.txt', 'w')
for line in f:
f2.write(line.rstrip() + ' ')
f2.close()
Although I'm already closing f2 file after writing the contents of f1 to it. So why does it affect the rest of the file operations in the code? And how does it still affect f1? As in, the lists in the end are neither populated by the text from f1 nor f2.
Edit 1: In my question, I already tried to close the second file thinking that it would be the cause of my problem, not the loop itself; while the other question didn't even have a loop to satisfy an answer to my question. Although the answers are somewhat the same, the answer in the other question doesn't show how to use the contents of the file repeatedly without having to reset the iterator using f.seek(0) to be able to use the contents in several loops like in my code above.
You're attempting to loop through the contents of f twice:
for line in f:
for linez in f:
... and you can't do it that way. The second loop will exit immediately, because you already read all of the lines; there are none left to read.
If you want to save the lines of a file and loop through them several times, use something like this:
all_lines = f.readlines()
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 9 years ago.
I want to read a file in python and put each new line into an array. I know how to do it in PHP, with the file(fn, FILE_IGNORE_NEW_LINES); function and it's FILE_IGNORE_NEW_LINES parameter, but how do I do it in Python?
When reading a file (line-by-line), usually the new line characters are appended to the end of the line, as you loop through it. If you want to get rid of them?
with open('filename.txt', 'r') as f:
for line in f:
line = line.strip('\n')
#do things with the stripped line!
This is the same as (In Python):
with open("file.txt", "r") as f:
for line in f:
line = line.rstrip("\n")
...
You want this:
with open('filename.txt', 'r') as f:
data = [line.replace('\n', '') for line in f]
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 8 years ago.
So in Ruby I can do the following:
testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end
How would one do that in Python?
testsite_array = []
with open('topsites.txt') as my_file:
for line in my_file:
testsite_array.append(line)
This is possible because Python allows you to iterate over the file directly.
Alternatively, the more straightforward method, using f.readlines():
with open('topsites.txt') as my_file:
testsite_array = my_file.readlines()
Just open the file and use the readlines() function:
with open('topsites.txt') as file:
array = file.readlines()
In python you can use the readlines method of a file object.
with open('topsites.txt') as f:
testsite_array=f.readlines()
or simply use list, this is same as using readlines but the only difference is that we can pass an optional size argument to readlines :
with open('topsites.txt') as f:
testsite_array=list(f)
help on file.readlines:
In [46]: file.readlines?
Type: method_descriptor
String Form:<method 'readlines' of 'file' objects>
Namespace: Python builtin
Docstring:
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.