I have the following code:
import re
#open the xml file for reading:
file = open('path/test.xml','r+')
#convert to string:
data = file.read()
file.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
file.close()
where I'd like to replace the old content that's in the file with the new content. However, when I execute my code, the file "test.xml" is appended, i.e. I have the old content follwed by the new "replaced" content. What can I do in order to delete the old stuff and only keep the new?
You need seek to the beginning of the file before writing and then use file.truncate() if you want to do inplace replace:
import re
myfile = "path/test.xml"
with open(myfile, "r+") as f:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
f.truncate()
The other way is to read the file then open it again with open(myfile, 'w'):
with open(myfile, "r") as f:
data = f.read()
with open(myfile, "w") as f:
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>", r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", data))
Neither truncate nor open(..., 'w') will change the inode number of the file (I tested twice, once with Ubuntu 12.04 NFS and once with ext4).
By the way, this is not really related to Python. The interpreter calls the corresponding low level API. The method truncate() works the same in the C programming language: See http://man7.org/linux/man-pages/man2/truncate.2.html
file='path/test.xml'
with open(file, 'w') as filetowrite:
filetowrite.write('new content')
Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.
Using truncate(), the solution could be
import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
#convert to string:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
f.truncate()
import os#must import this library
if os.path.exists('TwitterDB.csv'):
os.remove('TwitterDB.csv') #this deletes the file
else:
print("The file does not exist")#add this to prevent errors
I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.
See from How to Replace String in File works in a simple way and is an answer that works with replace
fin = open("data.txt", "rt")
fout = open("out.txt", "wt")
for line in fin:
fout.write(line.replace('pyton', 'python'))
fin.close()
fout.close()
in my case the following code did the trick
with open("output.json", "w+") as outfile: #using w+ mode to create file if it not exists. and overwrite the existing content
json.dump(result_plot, outfile)
Using python3 pathlib library:
import re
from pathlib import Path
import shutil
shutil.copy2("/tmp/test.xml", "/tmp/test.xml.bak") # create backup
filepath = Path("/tmp/test.xml")
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
Similar method using different approach to backups:
from pathlib import Path
filepath = Path("/tmp/test.xml")
filepath.rename(filepath.with_suffix('.bak')) # different approach to backups
content = filepath.read_text()
filepath.write_text(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>", content))
I am trying to write a program that will open a file and print its contents. I am having some trouble with defining it I suppose? If it is not telling me that "path" is not defined, then it is telling me that "new_dir" is not defined.
Here is the code:
import pathlib
def prog_info():
print("This program will open a file, read and print its contents.")
print("-----------------------------------------------------------")
prog_info()
file_path = new_dir / "numbers.txt"
file_path.parent.mkdir()
file_path.touch()
with path.open("numbers.txt", mode="r", encoding="utf-8") as file:
for line in file:
print(line.strip())
The file is going to have three numbers that will be printed:
22
14
-99
with open("filename or location", 'r') as my_file:
for line in my_file:
print(line)
I hope this helped you.
You don't need mode, and you don't need the import. All you need is the code provided
I have a directory that contains both xml and *.bat files. I would like to find and replace the string "-SNAPSHOT" in any xml or .bat file. I can do this in notepad ++ where I go to Find in Files, enter "-SNAPSHOT" for the Find object, and "pom.xml,.bat" in the filter type, and it does what I am trying to do. However, I'd like to be able to accomplish the same thing in a python script. What is the best approach for this? Thanks.
Try something like this:
import os
myfldr = "myfolder\\"
mydir = os.listdir(myfldr)
old = "-SNAPSHOT"
new = "NEW_STRING"
for file in mydir:
tempdoc = []
if (".xml" in file) or (".bat" in file):
path = myfldr + file
with open(path, "rt") as f:
for line in f:
line = line.replace(old, new)
tempdoc.append(line)
with open(path, "wt") as f:
f.writelines(tempdoc)
In that part of code I make the files txt and its working
import sys
for i in range(6):
file = open('teste{:d}.txt'.format(i), 'a')
sys.stdout = file
And now the problem, the files were created but in this part of code it didnt work, i can compile but the files are empty
for i in range(1,6):
f=open('100K_Array_{:d}.txt'.format(i), 'r')
alist = f.readlines()
quickSort(alist)
print(alist)
f.close()
It appears to me that you haven't closed your output file properly. You should either use
with open('teste{:d}.txt', 'a') as file:
...
in which case with statement will handle closing the file for you. Otherwise you need to add file.close() to your current code.
this is my code to open a file and get the text from it :
f = open("C:/Users/muthaharsh/Documents/Harsh/News
Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-
Mint.txt","r+")
text = f.readlines()
print(text)
but i keep getting the error :
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt'
What code do i write to be able to do this ?
Thanks in advance ...
It's the whitespace in the path to file. Either use
r"C:/Users/muthaharsh/Documents/Harsh/News Project/Part3/Testing_purposes/Downloads3/Are-you-being-churned-,-Mint.txt"
or remove the whitespace in the filepath.
If you are running the code on windows add r before your filepath string.
Another way is that you can provide your input file as system arguments.
import sys
file_name = sys.argv[1]
with open(file_name, 'r') as f1:
file_text = f1.read()
print(file_text)
eg: python program for reading the file
you can run the code considering script is saved as readFile.py:
D:\Programs>python readFile.py D:\test.txt
output: This is a sample file
Here is the text