首页 > 解决方案 > python如何删除文件中的空白行

问题描述

我正在尝试从文件中删除。

这就是我想要做的。

1.导入Easygui

2.放三种模式加退出

  1. 3 种模式是(查看、添加、删除)

除删除部分外,一切正常。这就是我所拥有的

    import easygui

    filea = open('GroceryList.txt', 'a')
    fr = open('GroceryList.txt', 'r')
    filer = open('GroceryList.txt', 'r')

    runinng = True
    while runinng:
      a = easygui.choicebox('Do you want to add, delete, or see your list?',
                    choices = ['add', 'delete', 'see', 'quit'])
     if a == 'add':
       ad = easygui.enterbox('What do you want to add')
       filea.write(ad)
       filea.write('\n')
    filea.close()
    filea = open('GroceryList.txt', 'a')


    elif a == 'delete':
       rn = easygui.enterbox('What are you going to delete?')
       rl = fr.readlines()
       for lines in fr:
         if rn in lines:
           line.split()
         fr.close()
         fr = open('GroceryList.txt', 'r')


   elif a == 'see':
     s = filer.readlines()
     easygui.msgbox(s)
   filer.close()
   filer = open('GroceryList.txt', 'r')

   elif a == 'quit':
    runinng = False
  filea.close()
  fr.close()
  filer.close()

不工作的部分是:

    elif a == 'delete':
rn = easygui.enterbox('What are you going to delete?')
rl = fr.readlines()
if rn in fr:
  line.remove()
fr.close()
fr = open('GroceryList.txt', 'r')

标签: pythoneasygui

解决方案


正如其他人在评论中提到的那样,只是提供了一个小脚本来消除您可能仍然存在的疑问

fr = open('GroceryList.txt', 'r')
rl = fr.readlines()
new_list_to_keep_rows=[]
for row in rl:
    #add rows to keep
    new_list_to_keep_rows.append(row) 

new_file = open('GroceryList_new.txt', 'w')# open file in write mode
for item in new_list_to_keep_rows:
    new_file.write("%s\n" % item)

当你确定你拥有一切时重命名文件。


推荐阅读