假设我有一个充满昵称的文本文件。如何使用Python从这个文件中删除特定的昵称?
当前回答
解决这个问题的方法只有一个:
with open("target.txt", "r+") as f:
d = f.readlines()
f.seek(0)
for i in d:
if i != "line you want to remove...":
f.write(i)
f.truncate()
该解决方案以r/w模式(“r+”)打开文件,并使用seek重置f指针,然后截断以删除最后一次写入之后的所有内容。
其他回答
你想从文件中删除特定的行,所以使用这个简短的代码片段,你可以很容易地删除任何带有句子或前缀(符号)的行。
with open("file_name.txt", "r") as f:
lines = f.readlines()
with open("new_file.txt", "w") as new_f:
for line in lines:
if not line.startswith("write any sentence or symbol to remove line"):
new_f.write(line)
按行号删除文件中的某一行。
用文件名和要删除的行号替换变量filename和line_to_delete。
filename = 'foo.txt'
line_to_delete = 3
initial_line = 1
file_lines = {}
with open(filename) as f:
content = f.readlines()
for line in content:
file_lines[initial_line] = line.strip()
initial_line += 1
f = open(filename, "w")
for line_number, line_content in file_lines.items():
if line_number != line_to_delete:
f.write('{}\n'.format(line_content))
f.close()
print('Deleted line: {}'.format(line_to_delete))
示例输出:
Deleted line: 3
获取文件的内容,用换行符将其分割成一个元组。然后,访问元组的行号,加入结果元组,并覆盖到文件。
您可以使用re库
假设您能够加载完整的txt文件。然后定义一个不需要的昵称列表,然后用空字符串“”替换它们。
# Delete unwanted characters
import re
# Read, then decode for py2 compat.
path_to_file = 'data/nicknames.txt'
text = open(path_to_file, 'rb').read().decode(encoding='utf-8')
# Define unwanted nicknames and substitute them
unwanted_nickname_list = ['SourDough']
text = re.sub("|".join(unwanted_nickname_list), "", text)
将文件行保存在一个列表中,然后从列表中删除要删除的行,并将剩余的行写入一个新文件
with open("file_name.txt", "r") as f:
lines = f.readlines()
lines.remove("Line you want to delete\n")
with open("new_file.txt", "w") as new_f:
for line in lines:
new_f.write(line)
推荐文章
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录
- 我如何告诉matplotlib我已经完成了一个情节?
- 如何在Python中记录源文件名称和行号
- Python: List vs Dict用于查找表
- 试图在Windows 10上运行Python时出现“权限被拒绝”
- 如何在Django中设置时区
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?