python - python如何删除文件中的空白行
问题描述
我正在尝试从文件中删除。
这就是我想要做的。
1.导入Easygui
2.放三种模式加退出
- 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')
解决方案
正如其他人在评论中提到的那样,只是提供了一个小脚本来消除您可能仍然存在的疑问
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)
当你确定你拥有一切时重命名文件。
推荐阅读
- java - 超时后重新发送消息
- c++ - 重构模板类,使用它的嵌套类作为另一个类的模板参数
- android - 如何在卸载(Android)时强制删除应用程序数据?
- javascript - 实现订阅 angular 的 observable 的最佳位置
- google-bigquery - 谷歌云大查询中的错误?
- mips - MIPS - 添加两个单精度浮点数而不使用 add.s
- java - 从属性中获取带有 url 的 Micronaut HttpClient
- swift - 快速在 Alertview 中创建和自定义 UITextfield
- r - 绘图图例文本不适合
- c# - 通过 EFCore 3 中的接口解析 DbContext