Python按索引号替换行

时间:2015-05-11 06:28:03

标签: python

在Python中是否可以用索引号替换文件中某行的内容?

像line.replace这样的程序可以做这个程序吗?

4 个答案:

答案 0 :(得分:3)

如果您希望计算迭代次数,则应使用enumerate()

with open('fin.txt') as fin, open('fout.txt', 'w') as fout:
    for i, item in enumerate(fin, 1):
        if i == 7: 
            item = "string\n" 
        fout.write(item)

答案 1 :(得分:0)

喜欢的东西:

count = 0
with open('input') as f:
    with open('output', 'a+') as f1:
        for line in f:
            count += 1
            if count == 7: 
                line = "string\n" 
            f1.write(line)

答案 2 :(得分:0)

from tempfile import mkstemp
from shutil import move
from os import remove, close

def replace(file_path, pattern, subst):
    # Create temp file
    fh, abs_path = mkstemp()
    with open(abs_path, 'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern, subst))
    close(fh)
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

您可以使用上述功能替换文件中的特定行,您可以在需要时调用此函数:

replace("path_of_File\\test.txt", "lien that needs to be changed", "changed to ")

希望这是你可能正在寻找的......

答案 3 :(得分:0)

我使用了上面的一些答案,并允许将用户输入放入文件中。这也打印出用户输入将替换的行。

请注意,filename是占位符的真实文件名。

import os, sys
editNum=int(editLine)
filename2="2_"+filename
with open(filename, "a+") as uf, open(filename2, "w+") as outf:
    for i, item in enumerate(uf, 1):
    #Starts for loop with the "normal" counting numbers at 1 instead of 0
        if i != editNum:
            #If the index number of the line is not the one wanted, print it to the other file
            outf.write(item)
        elif i == editNum:
            #If the index number of the line is the one wanted, ask user what to replace line with
            print(item)
            filereplace=raw_input("What do you want to replace this line with? ")
            outf.write(filereplace)
    #Removes old file and renames filename2 as the original file
    os.remove(filename)
    os.rename(filename2, filename)