This question already has answers here:
How to delete a specific line in a file?
(17 answers)
Closed 6 years ago.
So I'm attempting to clean up a text file that I have (it is actually a region file which can be loaded into the astronomy fits viewer DS9). I would like to remove/delete the entirety of any line/(s) which contain the keyword "red" in them, for an example:
image;circle(2384.21957861,231.579450647,10.3410929712) # color = red text = {24}
Would anyone know how this could be accomplished within python?
Open an outfile (outfile.txt) for writing, and open your input file (textfile.txt), going line by line through the input file scanning for the keyword (red). If red is not in the line it writes it to the outfile.
with open('outfile.txt', 'w') as o:
with open('textfile.txt') as f:
for line in f.readlines():
if 'red' not in line:
o.write(line)
Make sure the files are within the same directory as the python script.
Based on this answer suggested by #algor, you coul try:
f = open("textfile.txt","r+")
d = f.readlines()
f.seek(0)
for line in d:
if 'red' not in line:
f.write(i)
f.truncate()
f.close()
Related
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.
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.
This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 9 years ago.
I want to read a file in python and put each new line into an array. I know how to do it in PHP, with the file(fn, FILE_IGNORE_NEW_LINES); function and it's FILE_IGNORE_NEW_LINES parameter, but how do I do it in Python?
When reading a file (line-by-line), usually the new line characters are appended to the end of the line, as you loop through it. If you want to get rid of them?
with open('filename.txt', 'r') as f:
for line in f:
line = line.strip('\n')
#do things with the stripped line!
This is the same as (In Python):
with open("file.txt", "r") as f:
for line in f:
line = line.rstrip("\n")
...
You want this:
with open('filename.txt', 'r') as f:
data = [line.replace('\n', '') for line in f]
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
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)