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)
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
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.
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
I am trying to open several csv files in python using this code:
file= open('file.csv', "r")
contents= file.read()
allLines = file.readlines()
print(contents)
print(allLines)
But all python prints is "[]"
When I look in the folder for my python project- the file is there but it is now empty- what's going wrong?
With regards to why python is printing an empty array, I'm assuming that you only experience this when printing allLines . When using read operations on file that you've left open, Python leaves the read cursor at the end of the file. I believe if you use seek(0) you can return the read cursor back to the beginning of the file. i.e.:
file = open('file.csv', 'r')
contents = file.read()
file.seek(0)
allLines = file.readlines()
print(contents)
print(allLines)
This seems rather unusual that it would be removing your data since it is only reading. You shold try providing the full path to the file.
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)