Edit specific line in a big file - python

I want to edit a a big file in specific lines.
So it isnt a good Idea to read the whole file before editing, thats why I dont
want to use:
myfile.readlines()
I have to read each line check if there a special content in it and then i have to edit this line.
So far Im reading every line:
file = open("file.txt","r+")
i = 0
for line in file:
if line ......:
//edit this line
//this is where i need help
file.close()
So the Question is:
How can I edit the current line in the If Statement for example:
if the current line is "test" I want to replace it with "test2" and then write "test2" back into the file into the line where "test" was before

This will help
import fileinput
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
for line in file:
print(line.replace(text_to_search, replacement_text), end='')

ok so as #EzzatA mentioned in the comments below the question it seems to be the best way to read the original file and create a new one with the edited data.
So something like this:
original_file = open("example.txt","r")
new_file = open("example_converted.xml","w")
string_tobe_replace = "test"
replacement_string = "test2"
for line in original_file:
if string_tobe_replace in line:
new_line = line.replace(string_tobe_replace,replacement_string)
new_file.write(new_line)
else:
new_file.write(line)
original_file.close()
new_file.close()

Related

Insert new data for each text line in python

I have a text file that looks like this:
1,004,59
1,004,65
1,004,69
1,005,55
1,005,57
1,006,53
1,006,59
1,007,65
1,007,69
1,007,55
1,007,57
1,008,53
Want to create new text file that will be inserted by 'input', something like this
1,004,59,input
1,004,65,input
1,004,69,input
1,005,55,input
1,005,57,input
1,006,53,input
1,006,59,input
1,007,65,input
1,007,69,input
1,007,55,input
1,007,57,input
1,008,53,input
I have attempted something like this:
with open('data.txt', 'a') as f:
lines = f.readlines()
for i, line in enumerate(lines):
line[i] = line[i].strip() + 'input'
for line in lines:
f.writelines(line)
Not able to get the right approach though.
What you want is to be able to read and write to the file in place (at the same time). Python comes with the fileinput module which is good for this purpose:
import fileinput
for line in fileinput.input('data.txt', inplace=True):
line = line.rstrip()
print line + ",input"
Discusssion
The fileinput.input() function returns a generator that reads your file line by line. Each line ends up with a new line (either \n or \r\n, depends on the operating system).
The code then strip off each line of this new line, add the ",input" part, then print out. Note that because of fileinput magic, the print statement's output will go back into the file instead of the console.
There are a newline '\n' in every line in your file, so you should handle it.
edit: oh I forgot about the rstrip() function!
tmp = []
with open("input.txt", 'r') as file:
appendtext = ",input\n"
for line in file:
tmp.append(line.rstrip() + appendtext)
with open("input.txt", 'w') as file:
file.writelines(tmp)
Added:
Answer by Hai_Vu is great if you use fileinput since you don't have to open the file twice as I did.
To do only the thing you're asking I would go for something like
newLines = list()
with open('data.txt', 'r') as f:
lines = f.readlines()
for line in lines:
newLines.append(line.strip() + ',input\n')
with open('data2.txt', 'w') as f2:
f2.writelines(newLines)
But there are definitely more elegant solutions

Python not over-writing file

I am trying to overwrite individual lines of a particular file by replacing certain keywords within the line. I have already looked into multiple questions and most of the answers were showing what I have already implemented.
Following is the code:
with open(fileLocation,"r+") as openFile:
for line in openFile:
if line.strip().startswith("objectName:"):
line = re.sub(initialName.replace(".qml",""),camelCaseName.replace(".qml",""),line)
print line
openFile.write(line)
openFile.close()
You could save the text of the file to a string, save the changes to that strings and write the text once you are finished editing :)
finalText = "" # Here we will store the complete text
with open(fileLocation, "r") as openFile:
for line in openFile:
if line.strip().startswith("objectName:"):
line = ... # do whatever you want to do with the line.
finalText += line
and just do the following right after that:
with open(fileLocation, 'w') as openFile:
openFile.write(finalText)

Appends text file instead of overwritting it

The context is the following one, I have two text file that I need to edit.
I open the first text file read it line by line and edit it but sometimes when I encounter a specific line in the first text file I need to overwritte content of the the second file.
However, each time I re-open the second text file instead of overwritting its content the below code appends it to the file...
Thanks in advance.
def edit_custom_class(custom_class_path, my_message):
with open(custom_class_path, "r+") as file:
file.seek(0)
for line in file:
if(some_condition):
file.write(mu_message)
def process_file(file_path):
with open(file_path, "r+") as file:
for line in file:
if(some_condition):
edit_custom_class(custom_class_path, my_message)
In my opinion, simultaneously reading and modifying a file is a bad thing to do. Consider using something like this. First read the file, make modifications, and then overwrite the file completely.
def modify(path):
out = []
f = open(path)
for line in f:
if some_condition:
out.append(edited_line) #make sure it has a \n at the end
else:
out.append(original_line)
f.close()
with open(path,'w') as f:
for line in out:
f.write(line)

python adding a new line to the existing line

I tried every possible thing to add a new line at the end of the existing line, but i am not getting what i exactly need.
Coding:
def retrieve_input(self):
input1 = self.txt1.get("0.0",'end-1c')
with open('text.txt','r+') as f:
f.write(input1+" -d")#<-gettting wrong input
My file:
Hello ,how are you.
After adding a new line to input 1: "are you fine?"
Then it has to add as:
Hello ,how are you.
are you fine?
Please ,help me to fix it!
Try:
with open('text.txt','a+') as f:
f.write(input1+" -d")#<-gettting wrong
An example is enigmatic, I can only guess what it is.
My test file:
first line
second line
third line
My code:
with open('text.txt') as f:
for line in f:
print line+'\n'
Output:
first line
second line
third line
If you are using Windows change \n to \r\n

Python wierd file name on create

I have a txt file with list of html/doc files, I want to download them using python and save them as 1.html, 2.doc, 3.doc, ...
http://example.com/kran.doc
http://example.com/loj.doc
http://example.com/sks.html
I've managed to create fully functional script except python will allways add question mark to the end of newly created file (if you look from linux) and if you look from windows file name would be something like 5CFB43~X
import urllib2
st = 1;
for line in open('links.txt', 'r'):
u = urllib2.urlopen(line)
ext = line.split(".")
imagefile = str(st)+"."+ext[-1]
#file created should be something.doc but its something.doc? -> notice question mark
fajl = open(imagefile, "w+")
fajl.write(u.read())
fajl.close()
print imagefile
st += 1
The line terminator is two characters, not one.
for line in open('links.txt', 'rU'):
But not anymore.
Work on line.strip() instead of line
That's because lines read this way will end up with '\n' at the end, hence the ?
Just add the following at the beginning of your loop:
if line.endswith('\n'):
line = line[:-1]
Or as AKX pointed out in the comments, just:
line = line.rstrip('\r\n')
And so you cover any kind of line ending.

Categories