What is the difference between read() and readline() in python? [duplicate] - python

This question already has answers here:
When should I ever use file.read() or file.readlines()?
(5 answers)
Closed 3 years ago.
I am learning file handling in python right now. If i write read() method , it does work same as readline() method . There must be a difference between them and i want to learn that

This question has been answered countless times, and the documentation does a good job of describing the differences, too. But here goes:
If you have a file (test.txt) like so:
first line
second line
third line
Then this code:
with open("test.txt", "r") as file:
line = file.readline()
print(line)
Will produce this output:
first line
That's because readline just reads the next line.
If you use this code instead:
with open("test.txt", "r") as file:
content = file.read()
print(content)
Output:
first line
second line
third line
read() reads the entire contents of the file into a string.
You can also give read() an optional argument, which designates the number of characters to read from the file:
with open("test.txt", "r") as file:
content = file.read(15)
print(content)
Output:
first line
seco
Finally, the third function, which you didn't mention, is readlines, which returns a list of lines (strings):
with open("test.txt", "r") as file:
lines = file.readlines()
print(lines)
Output:
['first line\n', 'second line\n', 'third line\n']

The main difference is that read() will read the whole file at once and then print out the first characters that take up as many bytes as you specify in the parenthesis versus the readline() that will read and print out only the first characters that take up as many bytes as you specify in the parenthesis. You may want to use readline() when you're reading files that are too big for your RAM.

Related

Extracting the data from the same position over multiple lines in a string

Fairly simple question but I can't figure out where i'm going wrong. I have a text file which I have split into multiple lines. I want to print a certain location from each line, characters 14 to 20 but when I run the below code it prints a blank set of a characters.
with open('filetxt', 'r') as file:
data = file.read().rstrip()
for line in data:
print(line[14:20])
If you want to read the file line by line, try:
with open('filetxt', 'r') as file:
for line in file:
print(line[14:20])
I think you're using the wrong read() method. read() reads the whole file at once you might want to use readlines() which returns a list of the read lines. I.e.:
with open('filetxt', 'r') as file:
lines = file.readlines()
for line in lines:
print(line[14:20])

How to delete the last 4 characters from every line in a file? - Python [duplicate]

This question already has answers here:
Is it possible to modify lines in a file in-place?
(5 answers)
Closed 2 years ago.
Can anyone give me some advice on creating a loop to cut the last 4 characters from every line within an input file?
I have tried:
myfile = open('delete.txt', 'w+')
myfile.read()
for line in myfile:
line = line[:3]
myfile.close()
The file is formatted like thi:
Awks,1er,xyz,lon,thr,tkj,,^M
Atks,1er,xyz,lon,thr,toj,,^M
Ahks,1er,xyz,lon,thr,taj,,^M
Auks,1er,xaz,lon,thr,tej,,^M
Aqks,1er,xyz,lon,thr,twj,,,^M
Aoks,1er,xaz,lon,thr,twj,,^M
Apks,1er,xwz,lon,thr,trj,,^M
Alks,1er,xuz,lon,thr,toe,,^M
ssks,1er,xoz,lon,thr,toj,,^M
ssks,1er,xnz,lon,thr,tog,,,^M
As some comments said, it's probably safer to open up the input file and write output to a separate file.
Using a with block is handy, because you don't need to handle closing a file; your file is automatically closed at the end of the block.
I'd do something like this:
with open('input.txt', 'r') as infile:
with open('output.txt', 'w') as outfile:
for line in infile:
outfile.write(line[:-5])
outfile.write('\n')
The line[:-5] will remove the last five characters of each line, which is probably what you want since each line also contains a newline, so it removes the newline and four characters. We outfile.write('\n') because the newline was removed, and we want it back.

Multiple lines in file appearing as only one line [duplicate]

This question already has answers here:
write() versus writelines() and concatenated strings
(5 answers)
Closed 3 years ago.
I am trying to save some variables to a file on separate lines.
My code looks like this:
def saveall(sname, senemyname, scheckpoint,):
file = open("savefile.sav", "w")
file.writelines([sname, senemyname, scheckpoint])
file.close()
If I put saveall("John","Steve","Crossroads") in my code, I want it to make a file called savefile.sav, containing:
John
Steve
Crossroads
However, when I run the program, savefile.sav contains:
JohnSteveCrossroads
What am I doing wrong?
writelines expects each string to be newline terminated. So you need:
file.writelines([sname + '\n', senemyname + '\n', scheckpoint + '\n'])
From the python docs:
writelines(lines)
Write a list of lines to the stream. Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.
But usually it's more idiomatic to do file.write('\n'.join([sname, senemyname, scheckpoint)). Note that that doesn't add the file newline.
You should also be using contexts for files, because if an exception is raised you may not close your file:
with open('savefile.sav', 'w') as f:
f.write('\n'.join([sname, senemyname, scheckpoint]))
writelines doesn't add separators between the lines, so you have to add them yourself:
def saveall(sname, senemyname, scheckpoint,):
file = open("savefile.sav", "w")
file.writelines((line + '\n' for line in [sname, senemyname, scheckpoint]))
file.close()
saveall("John","Steve","Crossroads")
File content:
John
Steve
Crossroads

How to read text file line by line and do something for a particular line? [duplicate]

This question already has answers here:
How to jump to a particular line in a huge text file?
(17 answers)
Closed 8 years ago.
I want to read a text file line by line. I found how to read line by line by searching but not how to call a specific line in a text file. Basically, i want to do something with particular lines( like the first line, the second line, the third line, etc):
if particular_line is something:
....
Also, how can i do something like this:
if return_from_another_function in file:
....
Basically, i want an example of how i could do that if it's possible.
f = open('filename', 'r')
lines = f.readlines()
now you get a list type object lines which you can use to access particular line or iterate and search for particular line.
Probably this will help:
myfile = open(filename, "rb", 0)
for line in myfile
if(line is "your string to be compared")
print "do something here"
The standard linecache module makes this a snap:
import linecache
theline = linecache.getline(thefilepath, desired_line_number)
For your second que (from Ans):
If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):
if 'blabla' in open('example.txt').read():
print "true"

Combined effect of reading lines twice?

As a practice, I am learning to reading a file.
As is obvious from code, hopefully, I have a file in working/root whatever directory. I need to read it and print it.
my_file=open("new.txt","r")
lengt=sum(1 for line in my_file)
for i in range(0,lengt-1):
myline=my_file.readlines(1)[0]
print(myline)
my_file.close()
This returns error and says out of range.
The text file simply contains statements like
line one
line two
line three
.
.
.
Everything same, I tried myline=my_file.readline(). I get empty 7 lines.
My guess is that while using for line in my_file, I read up the lines. So reached end of document. To get same result as I desire, I do I overcome this?
P.S. if it mattersm it's python 3.3
No need to count along. Python does it for you:
my_file = open("new.txt","r")
for myline in my_file:
print(myline)
Details:
my_file is an iterator. This a special object that allows to iterate over it.
You can also access a single line:
line 1 = next(my_file)
gives you the first line assuming you just opened the file. Doing it again:
line 2 = next(my_file)
you get the second line. If you now iterate over it:
for myline in my_file:
# do something
it will start at line 3.
Stange extra lines?
print(myline)
will likely print an extra empty line. This is due to a newline read from the file and a newline added by print(). Solution:
Python 3:
print(myline, end='')
Python 2:
print myline, # note the trailing comma.
Playing it save
Using the with statement like this:
with open("new.txt", "r") as my_file:
for myline in my_file:
print(myline)
# my_file is open here
# my_file is closed here
you don't need to close the file as it done as soon you leave the context, i.e. as soon as you continue with your code an the same level as the with statement.
You can actually take care of all of this at once by iterating over the file contents:
my_file = open("new.txt", "r")
length = 0
for line in my_file:
length += 1
print(line)
my_file.close()
At the end, you will have printed all of the lines, and length will contain the number of lines in the file. (If you don't specifically need to know length, there's really no need for it!)
Another way to do it, which will close the file for you (and, in fact, will even close the file if an exception is raised):
length = 0
with open("new.txt", "r") as my_file:
for line in my_file:
length += 1
print(line)

Categories