Count line no. using python [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get line count cheaply in Python?
In my work i need to open a file and count no. of lines in that, i tried with this
Last_Line = len(open(File_Name).readlines())
It was working fine. Now i have a problem, actual no. of lines in the file is 453, but if i print Last_Line it is showing only 339. If i try
print linecache.getline(File_Name, 350)
it is displaying the contents of line no. 350.
I tried opening the file in all modes.
Whether its problem with file or with my logic?
Please help.
thank you

You have mixed line endings. Your IDE is treating them all as valid, while Python is not. Open the file with the universal newlines flag "U" to have Python take them all as valid line endings.
>>> f = open("file.txt", "w")
>>> f.write("a\rb\nc\r\nd\n\re\n")
>>> f.close()
>>> open("file.txt").readlines()
['a\rb\n', 'c\r\n', 'd\n', '\re\n']
>>> open("file.txt", 'rU').readlines()
['a\n', 'b\n', 'c\n', '\n', 'd\n', '\n', 'e\n']
The documentation for linecache does not appear to specify how it handles line endings. Empirically, it uses universal newlines:
>>> for n in range(1, 8):
... linecache.getline('file.txt', n)
...
'a\n'
'b\n'
'c\n'
'\n'
'd\n'
'\n'
'e\n'

Related

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.

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

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.

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"

How to remove line from the file in python [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Deleting a specific line in a file (python)
I need to delete the line contains number '2' from the file f=
2 3
5 6
7 2
4 5
When you want to edit a file, you make a new file with the correct data and then rename the new file as the old file. This is what serious programs like your text editor probably do. (Some text editors actually do even weirder stuff, but there's no use going into that.) This is because in many filesystems the rename can be atomic, so that under no circumstances will you end up with the original file being corrupted.
This would lead to code to the effect of
with open(orig_file) as f, open(working_file, "w") as working:
# ^^^ 2.7+ form, 2.5+ use contextlib.nested
for line in f:
if '2' not in line: # Is this exactly the criterion you want?
# What if a line was "12 5"?
working.write(line)
os.rename(working_file, orig_file)
You may want to use orig_file + '~' or the tempfile module for generating the working file.
with open('f', 'r+') as f:
data = ''.join(filter(lambda l: '2' not in l.strip().split(' '), f))
f.seek(0)
f.truncate(0)
f.write(data)
import fileinput
for line in fileinput.input('f',inplace =1):
line = line.strip()
if not '2' in line:
print line

Categories