Python Tex tfile [duplicate] - python

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 1 year ago.
I want to store the inputs in my text file every time I run it. But when I run the script the old inputs gets deleted! how can I fix this?
sample code:
name = input('Enter name: ')
f = open('test.txt', 'w')
f.write(name)
f.close()

You should open the file in append mode:
f = open('test.txt', 'at')
Notice the at, meaning append text. You have w mode, meaning write text (text is default), which first truncates the file. This is why your old inputs got deleted.

With the 'w' in the open() you create a new empty file everytime.
use open('test.txt', 'a+')
Also I would suggest you use the with statement:
name = input('Enter name: ')
with open('test.txt', 'a+') as file:
file.write(name)

write the additional text in append mode
f = open('test.txt', 'a')
'w' is write mode and so deletes any other data before rewriting any new data

Related

Why does my last data on csv get delete by python [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 2 years ago.
I'm new to python and I'm working on a little writing in CSV project
but every time that I run it it will delete my last data and write a new one
this is the code
with open('data.csv', 'w', newline='')as f:
User_new_pass = input('enter your new password: ').strip()
User_new_id = ' ' + input('enter your new user name: ').strip()
User_new_info = [User_new_pass, User_new_id]
linewriter = csv.writer(f)
linewriter.writerow(User_new_info)
If you want to append to the file, you should change the mode in the open() function:
with open('data.csv', 'a', newline='')as f:
# your code
a - Open file in append mode. If file does not exist, it creates a new file.
w - This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file.

Append text to a Text file without replacing it Python [duplicate]

This question already has answers here:
Prepend a line to an existing file in Python
(13 answers)
Closed 3 years ago.
Im new to python and I need some help from you guys.
So this is my Code
Tk().withdraw()
filename = askopenfilename(title='Choose a file', filetypes=[("Text Files", "*.txt")])
f = open(filename)
with open(filename,'r+',encoding="UTF-8") as file:
file.write('test')
file.write('\n')
file_contents = f.read()
This is the Text File without using file.write
Im a big noob in python please help me.
And this is after using file.write
test
ig noob in python please help me.
My Goal is to append the Text to the top of the text file without replacing the contect underneath it.
When you write to a file it always effectively overwrites the bytes inside the file stream. What you might want to do instead, is read the file first, and write the necessary parts, and then write your original contents back:
with open(filename,'r+',encoding="UTF-8") as file:
data = file.read()
file.write('test\n')
file.write(data)
This should be all you need. Remove the f = open(filename) and file_contents = f.read() lines, because you are opening the same file twice.
Just copy the content first and insert it in the beginning, like this:
with open(filename,'r+',encoding="UTF-8") as file:
previous_content = file.read()
file.write('test\n' + previous_content)

write function parameter inside file - Python [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 5 years ago.
I have a function which prints messages. then I want to save this messages into a file. But when I use .write(function parameter) it only write last message inside my file
writing_in_log = True
def print_and_log(message):
if write_in_log is True:
logFile = open("log", "w+")
logFile.write(message)
logFile.close()
I suppose you are not using the 'a' parameter when opening the file:
with open('file.txt', 'a') as file:
file.write('function parameter')
You probably open the file for each writing with open(yourfile, 'w') which will erase any content from the file before you write to it. If you want to append to your file, use open(yourfile, 'a').
In case this is not the error we need more information about what you are doing, i.e. the relevant parts of the code.

How to prevent print from overwriting a text file? [duplicate]

This question already has answers here:
How do I append to a file?
(13 answers)
Closed 8 years ago.
This code actually overwrite the pre-existing content of out.txt, is there a way to make it print in the next line ?
with open(r'C:\out.txt', "w") as presentList:
print("Hello", file=presentList)
Use "a" instead of "w".
This appends new text at the end.
I think you'll want to open with "r+" instead (opening with "w" overwrites the file!). If you aren't partial to using with, you can do
f = open("C:/out.txt","r+")
f.readlines()
f.write("This is a test\n")
f.close()
The f.readlines() will ensure that you write to the end of the file instead of overwriting the first line if you need to write more. As the other person said, you can also open with "a" too

Replace string within file contents [duplicate]

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)

Categories