首页 / PYTHON / python – 删除文件中的行
python – 删除文件中的行
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 删除文件中的行,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1736字,纯文字阅读大概需要3分钟。
内容图文
![python – 删除文件中的行](/upload/InfoBanner/zyjiaocheng/727/59494536207d4741a9f6146f2dfa8deb.jpg)
我想在文件中显示行,让用户决定应该删除哪一行,然后将所有行写回文件,除了用户想要删除的行.
这是我到目前为止所尝试的,但我有点卡住了.
def delete_result():
text_file = open('minigolf.txt', 'r')
zork = 0
for line in text_file:
zork = zork + 1
print zork, line
delete_player = raw_input ("Who's result do you want to delete?")
text_file.close()
要么
def delete_result():
text_file = open('minigolf.txt', 'r')
for line in text_file:
if ';' in line:
line2 = line.split(";")
print line2
print "***"
delete = raw_input ("Who's result do you want to delete? ")
text_file.close()
minigolf.txt包含:
Sara;37;32;47;
Johan;44;29;34;
Kalle;33;34;34;
Oskar;23;47;45;
解决方法:
这将解决您的问题,并为您提供更强大的处理用户输入的方式:
def delete_result():
with open('minigolf.txt', 'r') as f:
text_file = f.readlines()
# find newline char and strip from endings
if '\r' in text_file[0]:
if '\n' in text_file[0]:
newline = '\r\n'
else:
newline = '\r'
else:
newline = '\n'
text_file = [t[:-len(newline)]
if t[-len(newline):] == newline
else t for t in text_file]
users = set()
for line_number, line in enumerate(text_file):
print line_number + 1, line
users.add(line[:line.index(';')].lower())
# get result from user with exception handling
result = None
while not result:
delete_player = raw_input('Which user do you want to delete? ')
try:
result = str(delete_player).lower()
assert result in users
except ValueError:
print('Sorry, I couldn\'t parse that user.')
except AssertionError:
print('Sorry, I couldn\'t find that user.')
result = None
# write new file
new_file = [t + newline for t in text_file
if t[:t.index(';')].lower() != result]
with open('minigolf.txt', 'w') as f:
f.writelines(new_file)
if __name__ == '__main__':
delete_result()
编辑:我看到你想要按名称删除,而不是行号,所以改成它类似于@ danidee的方法.
内容总结
以上是互联网集市为您收集整理的python – 删除文件中的行全部内容,希望文章能够帮你解决python – 删除文件中的行所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。