Remove current line from file [duplicate] - python

This question already has answers here:
Is it possible to modify lines in a file in-place?
(5 answers)
Closed 2 years ago.
Consider a file with the following lines:
remove
keep
remove
Is it possible to remove the current line while iterating the file lines?
for word in file:
if word != "keep":
remove_line_from_file
In the end the file should just the line with word keep.
I know I could create a file with the remaining words but I was hoping to keep the same file.

Python has a nice library named fileinput which allows you to modify files inplace. You can print what you want to keep back into the file:
with fileinput.input(filename, inplace=True) as lines:
for line in lines:
if line == 'keep':
print(line,)

No, but you can extract all the contents of the file beforehand, modify the text, and then rewrite them back into the file:
with open('file.txt','r') as f:
lines = f.readlines()
with open('file.txt','w') as f:
f.write(''.join([ln for ln in lines if 'keep' in ln])) # Writes all the lines back to file.txt that has the word `keep` in them

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.

How to read each line in a file backwards using Python [duplicate]

This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 3 years ago.
I'm trying to read a file (example below), line by line, backwards using Python.
abcd 23ad gh1 n d
gjds 23iu bsddfs ND31 NG
Note: I'm not trying to read the file from the end to the beginning, but I want to read each line starting from the end, i.e d for line 1, and NG for line 2.
I know that
with open (fileName) as f:
for line in f:
reads each line from left to right, I want to read it from right to left.
Try this:
with open(fileName, 'r') as f:
for line in f:
for item in line.split()[::-1]:
print(item)
If your file is not too big, you can read lines in reverse easily
with open(fileName) as f:
for line in reversed(f.readlines()):
# do something
Otherwise, I believe you'd have to use seed.

print list line by line in python [duplicate]

This question already has answers here:
How to read a large file - line by line?
(11 answers)
Closed 4 years ago.
I am new in python and I am trying to print a list line by line.
fp = open(filepath) # Open file on read mode
lines = fp.read().split("\n") #Create a list with each line
print(lines) #Print the list
for line in lines:
print(line) #Print each line
fp.close()
But it's printing in one line.
The contents of the text file are
peat1,1,11345674565,04-11-2018
peat2,0,11345674565,05-11-2018
peat3,1,11345674565,06-11-2018
peat4,0,11345674565,07-11-2018
And it is printing as
peat1,1,11345674565,04-11-2018 peat2,0,11345674565,05-11-2018 peat3,1,11345674565,06-11-2018 peat4,0,11345674565,07-11-2018
The environment is -- Python 3.4 and running under Apache through cgi-bin
Any help is highly appreciated.
With large files, you are better off reading files line by line, like so:
with open('filename') as file:
for line in file:
print(line)
I suggest this approach with with, which handles closing the file pointer itself.

How to save line by line a file.txt in array or table? [duplicate]

This question already has answers here:
How to read the entire file into a list in python?
(6 answers)
Closed 5 years ago.
I would like to save a file.txt line by line in variable (array or list)
.So if the file.txt is:
hi there
what's up
I want my code to save it line by line in the same variable making a table so I can access easily each line when I want using that variable. And what can I do if I wanna access only line 2? It is supposed I don't know how many lines the file.txt has.
Thank you very much!
Well it is super easy in Python:
text_file = open("filename.txt", "r")
# Splits the element by "\n"
lines = text_file.readlines()
text_file.close()
#Print List of Lines in your File
print(lines)
#Print Number of Lines in your File
print(len(lines))
#Access Second Line in your file
print(lines[1])# Since python is zero indexed

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"

Categories