简体   繁体   English

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

[英]How do I delete specific records from a file in Python?

My program looks like this. 我的程序看起来像这样。 I have to delete three records from the numbers.txt file, which are "16", "17", and "18" by implementing a temp.txt file, as well as replace "10" with "50". 我必须通过实现temp.txt文件从numbers.txt文件中删除三个记录,分别是“ 16”,“ 17”和“ 18”,并用“ 50”替换“ 10”。 I'm stumped. 我很沮丧

   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()

Instead of this: 代替这个:

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

Do this: 做这个:

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

As for the overwriting 10 with 50 part, you could use a simple if statement to replace the value of each_line : 至于覆盖10的50部分,您可以使用一个简单的if语句来替换each_line的值:

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

But let's pretend like you need to replace a lot of values and you need a more scalable solution: 但是,让我们假装您需要替换很多值,并且需要一个更具扩展性的解决方案:

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

The second parameter to get() causes the value to be left alone if it's not in the dict. get()的第二个参数将导致该值不存在于dict中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM