如何从Python中删除文件中的特定记录?

时间:2015-04-18 20:56:12

标签: python file-io

我的程序看起来像这样。我必须通过实现temp.txt文件从numbers.txt文件中删除三个记录,即“16”,“17”和“18”,并将“10”替换为“50”。我很难过。

   import os
   import fileinput


   def main():

    # Create a numbers.txt file and write the numbers 1 through 10 to it
    number_file = open("numbers.txt", 'w')
    for n in range(1, 11):
        number_file.write(str(n) + '\n')
        number_file.close()

    # Read the data from the file and print the total of all the numbers
    number_file = open("numbers.txt", 'r')
    total = 0
    line = number_file.readline()
    while line != "":
        amount = float(line)
        print(amount)
        total += amount
        line = number_file.readline()
    print(total)
    number_file.close()

    # Add the numbers 11 through 20
    number_file = open("numbers.txt", 'a')
    for n in range (11, 21):
        number_file.write(str(n) + '\n')
    number_file.close()

    # Remove 16, 17, 18 and overwrite 10 with 50
    temporary_file = open("temp.txt", 'w')
    number_file = open("numbers.txt", 'r')    
    line = number_file.readline()
    each_line = line.rstrip('\n')
    while each_line != "" and each_line != "16" and each_line != "17" and each_line != "18":
        temporary_file.write(line)
        line = number_file.readline()
    temporary_file.close()
    number_file.close()
    os.remove("numbers.txt")
    os.rename("temp.txt", "numbers.txt")

main()

1 个答案:

答案 0 :(得分:0)

而不是:

while each_line != "" and each_line != "16" and each_line != "17" and each_line != "18":

这样做:

if each_line not in ["16", "17", "18"]:
    temporary_file.write(each_line + "\n")

对于50个部分的覆盖10,您可以使用简单的if语句来替换each_line的值:

if each_line == "10":
    each_line = "50"

但是,让我们假装你需要替换 lot 的值,你需要一个更具伸缩性的解决方案:

replacements = {"10": "50"}
# in the loop:
each_line = replacements.get(each_line, each_line)

get()的第二个参数会导致该值保持不变,如果它不在dict中。