This question already has answers here:
How to delete a specific line in a file?
(17 answers)
Closed 4 years ago.
Let's say I have a text file full of random lines. How can I keep a specific line and delete the others from this file, using Python?
The script should search for all .txt files from a directory/and sub directory.
Firstly, to search for all .txt files, you can use this:
import glob, os
os.chdir("/mydir")
for filePath in glob.glob("*.txt"):
...
Sourced from here
Secondly, to look through a file and find the line you want, use:
myfile = open(filePath, "r")
And look to see if your desired line is in the file.
if desiredLine in myfile:
...
Then you can close the file and reopen it in write mode.
myfile.close()
myfile = open(filePath, "w")
Then all you have to do is write the line you wanted to keep.
myfile.write(desiredLine)
Then close the file again
myfile.close()
Sourced from here
The final script ends up like this:
import glob, os
os.chdir("/mydir")
for filePath in glob.glob("*.txt"):
myfile = open(filePath, "r")
if desiredLine in myfile:
myfile.close()
myfile = open(filePath, "w")
myfile.write(desiredLine)
myfile.close()
Note, if your line doesn't exist in the file you're checking, it is left as is.
Hope this helps you
Related
This question already has answers here:
generalize python script to run on all files in a directory
(2 answers)
Closed 8 months ago.
i have this code that takes in a text folder and takes the 25th element in the first line of the file and place it in the 7th. However, this code opens only one text file and writes it to another but what i want that the code reads all the files in the folder and writes them in the same path.
index= 1
with open("3230c237cnc274c.txt", "r") as f:
file = f.readlines()
line = file[index].split(';')
target = line[24]
blank = line[6]
line[6] = target
line[24] = ""
file[index] = ';'.join(line)
with open("aaaaaaaaaaaaaaaa.txt", 'w') as f:
for line in file:
f.write(line)
I like to use the glob module for things like this. See if this helps:
import glob
all_text_files = glob.glob("*.txt")
for text_file in all_text_files:
with open(text_file, "r") as f:
lines = f.readlines()
# do something with the lines...
The syntax "*.txt" indicates all files ending with the .txt extension. This then returns a list of all those filenames. If your files are in a folder somewhere, you can also do "folder/*.txt", and there's a few other nice tricks with glob
What sort of loop would I use? I have tried some sort of for loop but I cannot get my code to review each file and keep going through all of the files. I have hundreds of files that I need analyzed. I saw somewhere that someone used this code:
import glob
import gzip
ZIPFILES='name.gz'
filelist = glob.glob(ZIPFILES)
for gzfile in filelist:
# print("#Starting " + gzfile) #if you want to know which file is being processed
with gzip.open(gzfile, 'r') as f:
for line in f:
print(line)
but how do I loop this to keep reading more files.
You can use glob to get a list of all the files in a directory, and then iterate over that list.
for filename in glob.glob('*.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
print(line)
This question already has answers here:
How do I append to a file?
(13 answers)
Closed 1 year ago.
I have 500 text files in one folder, each of them looks like this:
1-1,2-4,In,_,
1-2,5-9,this,_,
1-3,10-15,paper,_,
1-4,16-18,we,_,
1-5,19-26,propose,_,
1-6,27-28,a,Project[1],
I need to add one word at the end of the text in each of the files. The result I expect is:
1-1,2-4,In,_,
1-2,5-9,this,_,
1-3,10-15,paper,_,
1-4,16-18,we,_,
1-5,19-26,propose,_,
1-6,27-28,a,Project[1],
end
How do I write inside the with block?
import os
path = "All_TSV_Files"
files = [file for file in os.listdir(path) if file.endswith(".txt")]
for file in files:
with open(os.path.join(path, file), 'r',encoding='utf-8') as f:
### add "end" to end of the file
or should I use pandas data frame to do them?
Say your file is called "foo.txt", you can open it with intend of appending to it like this:
with open("foo.txt", "a") as f:
f.write("\nend")
The \n denotes a newline before inserting end.
This answer should be helpful:
Write to the last line of a text file?
Just open file in append mode (pointer will be in the ned of file) and write line.
I have a text file (filenames.txt) which contains over 200 file paths:
/home/chethan/purpose1/script1.txt
/home/chethan/purpose2/script2.txt
/home/chethan/purpose3/script3.txt
/home/chethan/purpose4/script4.txt
Out of the multiple lines present in each of these files, each of them contain a line which is a filename like Reference.txt. My objective is to replace .txt in Reference.txt with .csv in every file. As a beginner of Python I referred to several questions in stackoverflow on similar cases and wrote the following code.
My code:
#! /usr/bin/python
#filename modify_hob.py
import fileinput
f = open('/home/chethan/filenames.txt', 'r')
for i in f.readlines():
for line in fileinput.FileInput(i.strip(),inplace=1):
line = line.replace("txt","csv"),
f.close()
f.close()
When I run my code, the contents of txt files (script1, script2..) mentioned above are wiped away, i.e., they won't be having a single line of text inside them! I am puzzled with this behavior and not able to find out a solution.
This should get you going (untested):
#! /usr/bin/python
#filename modify_hob.py
# Open the file with filenames list.
with open('filenames.txt') as list_f:
# Iterate over the lines, each line represents a file name.
for filename in list_f:
# Rewrite its content.
with open(filename) as f:
content = f.read()
with open(filename, 'w') as f:
f.write(content.replace('.txt', '.csv'))
In your code below, f is set to the open file object of filename.txt and
nothing else. That is what you are closing in both the last two lines.
Also, you are not writing anything back to the files, so you can't expect your
changes to be written back to the disk. (Unless the fileinput module does some
dark magic that I'm missing.)
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)