[英]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.