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

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

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.

Remove current line from file [duplicate]

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

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

Count line no. using python [duplicate]

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'

Replace string within file contents [duplicate]

This question already has answers here:
Replacing instances of a character in a string
(17 answers)
How to search and replace text in a file?
(22 answers)
How to read a large file - line by line?
(11 answers)
Writing a list to a file with Python, with newlines
(26 answers)
Closed 7 months ago.
How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"?
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:
I am using the with statement in this example, which closes the file after the with block is terminated - either normally when the last command finishes executing, or by an exception.
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.
#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName, "w") as f:
f.write(newText)
Using pathlib (https://docs.python.org/3/library/pathlib.html)
from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))
If input and output files were different you would use two different variables for read_text and write_text.
If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.
If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.
Something like
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
with open('Stud.txt','r') as f:
newlines = []
for line in f.readlines():
newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
for line in newlines:
f.write(line)
If you are on linux and just want to replace the word dog with catyou can do:
text.txt:
Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Linux Command:
sed -i 's/dog/cat/g' test.txt
Output:
Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
Original Post: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where 'A' would be stored) you do...
import re
input = file('C:\full_path\Stud.txt', 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first.
saved_input
for eachLine in input:
saved_input.append(eachLine)
#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
search = re.sub('A', 'Orange', saved_input[i])
if search is not None:
saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt', 'w')
for each in saved_input:
input.write(each)

Categories