Python not over-writing file - python

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)

Related

How do i read a specific line of text from a file and use it as a parameter for a function

I am working on a Python script ( 2.7 ) that will take a line of text from a text file and use it as a parameter for a function but i can not seem to figure out how to pass the line as a parameter for the function
I also was wondering how would i modify a line that already exists in a file without opening it using a text editor within Python
#!/usr/bin/python
data = open("/tmp/INFO.txt", 'r')
Line = data.readlines()[2]
print Line
To get the specific line:
f = open("yourFile.txt", "r")
line = f.readlines()[yourLineNumber]
f.close()
To pass it as a parameter:
yourFunction(line)
To read a specific line and use it as a parameter, you first need to open the file then read the contents.
with open(filePath, 'r') as fd:
fileContents = fd.readlines()
Then you can can call fileContents[n] where n is the index of the line you need.

Edit specific line in a big file

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()

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

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)

how do you open .txt file in python in one line

I'm trying to open .txt file and am getting confused with which part goes where. I also want that when I open the text file in python, the spaces removed.And when answering could you make the file name 'clues'.
My first try is:
def clues():
file = open("clues.txt", "r+")
for line in file:
string = ("clues.txt")
print (string)
my second try is:
def clues():
f = open('clues.txt')
lines = [line.strip('\n') for line in open ('clues.txt')]
The thrid try is:
def clues():
f = open("clues.txt", "r")
print f.read()
f.close()
Building upon #JonKiparsky It would be safer for you to use the python with statement:
with open("clues.txt") as f:
f.read().replace(" ", "")
If you want to read the whole file with the spaces removed, f.read() is on the right track—unlike your other attempts, that gives you the whole file as a single string, not one line at a time. But you still need to replace the spaces. Which you need to do explicitly. For example:
f.read().replace(' ', '')
Or, if you want to replace all whitespace, not just spaces:
''.join(f.read().split())
This line:
f = open("clues.txt")
will open the file - that is, it returns a filehandle that you can read from
This line:
open("clues.txt").read().replace(" ", "")
will open the file and return its contents, with all spaces removed.

Categories