Python用indecie替换一行文件

时间:2014-05-14 20:35:42

标签: python replace

所以基本上我试图弄清楚打开文件的最佳方法,并说用其他东西替换文件的第一行。不幸的是,我遇到的所有内容都使用.replace,只有在您知道要替换的字符串时才能使用.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)

3 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

替换文件的特定行,这取决于您知道哪一行。

如果您知道该行号:

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

答案 2 :(得分:0)

好的,所以我用它来工作:

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