so basically I'm trying to figure out the best way to open a file and say replace the first line of the file with something else. Unfortunately, everything I come across uses .replace which only works if you know the string you want to replace. What is the best method if I know what line it appears on in the document and just want to replace that line with something else?
Code I have so far:
files = os.listdir(root.dirname)
files = [s for s in files if ".xml" in s]
print (files)
for x in range(len(files)):
with open(os.path.join(root.dirname,files[x]),"r+") as f:
old = f.read()
f.seek(0)
You can:
# Open a file.
f = open("file.txt")
# Read all the lines.
lines = f.readlines()
# Replace the first.
lines[0] = "replacing text"
# Close.
f.close()
# Open for writting.
f = open("file.txt", "w")
# Write
for line in lines:
f.write(line)
# Close
f.close()
To replace a particular line of a file that depends how you know which line.
If you know the number of the line:
def replace_in_file(filename, idx, new_line):
f = open(filename, "r")
lines = f.readlines()
f.close()
lines[idx] = new_line + "\n"
f = open("file", "w")
f.write("".join(lines))
f.close()
replace_in_file("file", 0, "new line content")
You can use the function replace_in_file
providing the file name filename
, the index idx
of the line to change and the new content new_line
you want.
Ok so I got it working using this:
def replace_in_file(filename, idx, new_line):
f = open(filename, "r")
lines = f.readlines()
f.close()
lines[idx] = new_line + "\n"
f = open(filename, "w")
for line in lines:
write=line
f.write(write)
f.close()
files = os.listdir(root.dirname)
files = [s for s in files if ".xml" in s]
for x in range(len(files)):
#with open(os.path.join(root.dirname,files[x]),"r+") as f:
file = os.path.join(root.dirname,files[x])
print("Fixing "+file)
replace = '<?xml-stylesheet type="text/xsl" href="'+root.filename+'"?>'
replace_in_file(file, 0, replace)
with open(os.path.join(root.dirname,files[x]),"r+") as f:
old = f.read()
f.close
with open(os.path.join(root.dirname,files[x]),"w") as f:
f.write('<?xml version="1.0" encoding="UTF-8"?>\n'+old)
f.close
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.