Appends text file instead of overwritting it - python

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)

Related

ValueError: must have exactly one of create/read/write/append mode

I have a file that I open and i want to search through till I find a specific text phrase at the beginning of a line. I then want to overwrite that line with 'sentence'
sentence = "new text" "
with open(main_path,'rw') as file: # Use file to refer to the file object
for line in file.readlines():
if line.startswith('text to replace'):
file.write(sentence)
I'm getting:
Traceback (most recent call last):
File "setup_main.py", line 37, in <module>
with open(main_path,'rw') as file: # Use file to refer to the file object
ValueError: must have exactly one of create/read/write/append mode
How can I get this working?
You can open a file for simultaneous reading and writing but it won't work the way you expect:
with open('file.txt', 'w') as f:
f.write('abcd')
with open('file.txt', 'r+') as f: # The mode is r+ instead of r
print(f.read()) # prints "abcd"
f.seek(0) # Go back to the beginning of the file
f.write('xyz')
f.seek(0)
print(f.read()) # prints "xyzd", not "xyzabcd"!
You can overwrite bytes or extend a file but you cannot insert or delete bytes without rewriting everything past your current position.
Since lines aren't all the same length, it's easiest to do it in two seperate steps:
lines = []
# Parse the file into lines
with open('file.txt', 'r') as f:
for line in f:
if line.startswith('text to replace'):
line = 'new text\n'
lines.append(line)
# Write them back to the file
with open('file.txt', 'w') as f:
f.writelines(lines)
# Or: f.write(''.join(lines))
You can't read and write to the same file. You'd have to read from main_path, and write to another one, e.g.
sentence = "new text"
with open(main_path,'rt') as file: # Use file to refer to the file object
with open('out.txt','wt') as outfile:
for line in file.readlines():
if line.startswith('text to replace'):
outfile.write(sentence)
else:
outfile.write(line)
Not the problem with the example code, but wanted to share as this is where I wound up when searching for the error.
I was getting this error due to the chosen file name (con.txt for example) when appending to a file on Windows. Changing the extension to other possibilities resulted in the same error, but changing the file name solved the problem. Turns out the file name choice caused a redirect to the console, which resulted in the error (must have exactly one of read or write mode): Why does naming a file 'con.txt' in windows make Python write to console, not file?

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

how to make a .text file in terminal python3.33

I was wondering how to make a .text file so I can put words in it and then in my program open the file. I just need to know how to make a .text file!
Anyone know why my code won't open my .txt file when I try to run it?
def readWords(filename):
words = []
wordFile = open(words.txt, "r")
for line in wordFile:
line = line.upper()
words.extend(string.split(line))
wordFile.close()
return words
with open('myfile.txt', 'w') as f:
f.write('potato')
Opening a file in write mode will create it for you if it doesn't already exist:
with open("/path/to/file.txt", "w") as myfile:
# Do whatever
In the above code, myfile will be the file object.
Here is a reference on open and one on with.

python printing a blank line on the first line when writing to a file

I'm stuck on why my code is printing a blank line before writing text to a file. What I am doing is reading two files from a zipped folder and writing the text to a new text file. I am getting the expected results in the file, except for the fact that there is a blank line on the first line of the file.
def test():
if zipfile.is_zipfile(r'C:\Users\test\Desktop\Zip_file.zip'):
zf = zipfile.ZipFile(r'C:\Users\test\Desktop\Zip_file.zip')
for filename in zf.namelist():
with zf.open(filename, 'r') as f:
words = io.TextIOWrapper(f)
new_file = io.open(r'C:\Users\test\Desktop\new_file.txt', 'a')
for line in words:
new_file.write(line)
new_file.write('\n')
else:
pass
zf.close()
words.close()
f.close()
new_file.close()
Output in new_file (there is a blank line before the first "This is a test line...")
This is a test line...
This is a test line...
this is test #2
this is test #2
Any ideas?
Thanks!
My guess is that the first file in zf.namelist() doesn't contain anything, so you skip the for line in words loop for that file and just do new_file.write('\n'). It's difficult to tell without seeing the files that you're looping over; perhaps add some debug statements that print out the files' names and some info, e.g. their size.

Reading and writing to a file

I have an XML file that contains an illegal character, I am iterating through the file, removing the character from all of the lines and storing the lines in a list. I now want to write those same lines back into the file and overwrite what is already there.
I tried this:
file = open(filename, "r+")
#do stuff
Which is only appending the results to the end of the file, I would like to overwrite the existing file.
And this:
file = open(filename, "r")
#read from the file
file.close()
file = open(filename, "w")
#write to file
file.close()
This gives me a Bad File Descriptor error.
How can i read and write to the same file?
Thanks
You could re-write the lines list with writelines function.
with open(filename, "r") as f:
lines = f.readlines()
#edit lines here
with open(filename, "w") as f:
f.writelines(lines)
The reason you're appending to the end of the file the whole time is that you need to seek to the beginning of the file to write your lines out.
with open(filename, "r+") as file:
lines = file.readlines()
lines = [line.replace(bad_character, '') for line in lines]
file.seek(0)
file.writelines(lines)
file.truncate() # Will get rid of any excess characters left at the end of the file due to the length of your new file being shorter than the old one, as you've removed characters.
(Decided to just use the context manager syntax myself.)

Categories