[英]Python replace a line of file by indecie
因此,基本上,我正在嘗試找出打開文件的最佳方法,並說用其他內容替換文件的第一行。 不幸的是,我遇到的所有東西都使用.replace,只有當您知道要替換的字符串時,它才起作用。 如果我知道它出現在文檔的哪一行,並且只想用其他內容替換那行,什么是最佳方法?
我到目前為止的代碼:
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)
您可以:
# 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()
替換文件的特定行,具體取決於您知道哪一行。
如果您知道行號:
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")
您可以使用函數replace_in_file
提供文件名filename
,要更改的行的索引idx
和所需的新內容new_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(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.