Reputation: 274
I'm trying to understand what's going on with my read
function. I'm simply doing a readline
of a text document I created in canopy. For some reason it only gives me w
for whatever value I put in. I'm new to the world of Python so I'm sure its an easy answer! Thanks for your help!
import os
my_file = open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r')
print my_file.readline(3)
my_file.close()
My Text document is below
w
o
r
d
s
Upvotes: 1
Views: 105
Reputation: 879471
my_file.readline(3)
reads up to 3 bytes from the first line.
The first line contains a w
and an end-of-line character.
If you want to read up to the first 3 bytes regardless of the line, use my_file.read(3)
. Note that end-of-line characters are included in the count.
If you want to print the first 3 lines, you could use
import os
with open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r') as my_file:
for i, line in enumerate(my_file):
if i >= 3: break
print(line)
or
import itertools as IT
with open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r') as my_file:
for line in IT.islice(my_file, 3):
print(line)
For short files you could instead use
with open(os.path.expanduser("~/Desktop/Python Files/Test Text.txt"),'r') as my_file:
lines = my_file.readlines()
for line in lines[:3]:
print(line)
but note that my_file.readlines()
returns a list of all the lines in the
file. Since this can be very memory-intensive if the file is huge, and since it
is usually possible to process a file line-by-line (which is much less
memory-intensive), generally the first two methods of reading a file are
preferred over the third.
Upvotes: 5
Reputation: 20339
'readline([size]) -> next line from the file, as a string.Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then).Return an empty string at EOF.
readline
reads next line and so on.The argument size
is for how many bytes should it read from the corresponding line.
Upvotes: 1
Reputation: 6693
Using f.readline
does not give random access to the file. I think you want to read the third (or maybe fourth if you're zero-indexing) line. The argument that you're passing to f.readline
is a maximum byte count to read, rather than a specific line to read.
Upvotes: 0