假设我有一个充满昵称的文本文件。如何使用Python从这个文件中删除特定的昵称?
首先,打开文件并从文件中获取所有的行。然后以写模式重新打开文件,写回你想要删除的行:
with open("yourfile.txt", "r") as f:
lines = f.readlines()
with open("yourfile.txt", "w") as f:
for line in lines:
if line.strip("\n") != "nickname_to_delete":
f.write(line)
您需要去掉比较中的换行符(“\n”),因为如果您的文件不以换行符结束,那么最后一行也不会以换行符结束。
一般来说,你不能;您必须重新编写整个文件(至少从更改点到末尾)。
在某些特定的情况下,你可以做得比这个更好
如果所有的数据元素都是相同的长度,并且没有特定的顺序,并且您知道要删除的数据元素的偏移量,那么您可以将最后一项复制到要删除的数据元素之上,并在最后一项之前截断文件;
或者你可以用“这是坏数据,跳过它”的值覆盖数据块,或者在保存的数据元素中保留“此项已删除”的标记,这样你就可以在不修改文件的情况下标记它已删除。
对于短文档(小于100 KB的文档?)来说,这可能有点过分了。
在第一次传递中读取行并在第二次传递中进行更改(删除特定行)的问题是,如果文件大小很大,则会耗尽RAM。相反,更好的方法是逐行读取,并将它们写入单独的文件,删除不需要的文件。我曾经在12- 50gb大的文件上运行过这种方法,RAM使用几乎保持不变。只有CPU周期显示正在进行的处理。
在我看来,最好和最快的选择是在其他地方重写文件,而不是将所有内容存储在一个列表中并重新打开文件来写入。
with open("yourfile.txt", "r") as file_input:
with open("newfile.txt", "w") as output:
for line in file_input:
if line.strip("\n") != "nickname_to_delete":
output.write(line)
就是这样!在一个且只有一个循环中,你可以做同样的事情。这样会快得多。
我喜欢下面解释的文件输入方法: 从文本文件中删除一行(python)
例如,我有一个文件,其中有空行,我想删除空行,这是我如何解决它:
import fileinput
import sys
for line_number, line in enumerate(fileinput.input('file1.txt', inplace=1)):
if len(line) > 1:
sys.stdout.write(line)
注意:在我的例子中,空行长度为1
解决这个问题的方法只有一个:
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指针,然后截断以删除最后一次写入之后的所有内容。
也许你已经有了正确答案,但下面是我的答案。 我没有使用列表来收集未经过滤的数据(readlines()方法所做的),而是使用了两个文件。一个用于保存主数据,第二个用于在删除特定字符串时过滤数据。这是一个代码:
main_file = open('data_base.txt').read() # your main dataBase file
filter_file = open('filter_base.txt', 'w')
filter_file.write(main_file)
filter_file.close()
main_file = open('data_base.txt', 'w')
for line in open('filter_base'):
if 'your data to delete' not in line: # remove a specific string
main_file.write(line) # put all strings back to your db except deleted
else: pass
main_file.close()
希望你会发现这有用!:)
如果您使用Linux,可以尝试以下方法。 假设你有一个名为animal.txt的文本文件:
$ cat animal.txt
dog
pig
cat
monkey
elephant
删除第一行:
>>> import subprocess
>>> subprocess.call(['sed','-i','/.*dog.*/d','animal.txt'])
然后
$ cat animal.txt
pig
cat
monkey
elephant
我认为如果你把文件读入一个列表,然后你可以遍历这个列表来寻找你想要去掉的昵称。您可以在不创建额外文件的情况下高效地执行此操作,但必须将结果写回源文件。
以下是我可能的做法:
import, os, csv # and other imports you need
nicknames_to_delete = ['Nick', 'Stephen', 'Mark']
我假设nicknames.csv包含如下数据:
Nick
Maria
James
Chris
Mario
Stephen
Isabella
Ahmed
Julia
Mark
...
然后将文件加载到列表中:
nicknames = None
with open("nicknames.csv") as sourceFile:
nicknames = sourceFile.read().splitlines()
接下来,迭代到list以匹配要删除的输入:
for nick in nicknames_to_delete:
try:
if nick in nicknames:
nicknames.pop(nicknames.index(nick))
else:
print(nick + " is not found in the file")
except ValueError:
pass
最后,将结果写回文件:
with open("nicknames.csv", "a") as nicknamesFile:
nicknamesFile.seek(0)
nicknamesFile.truncate()
nicknamesWriter = csv.writer(nicknamesFile)
for name in nicknames:
nicknamesWriter.writeRow([str(name)])
nicknamesFile.close()
将文件行保存在一个列表中,然后从列表中删除要删除的行,并将剩余的行写入一个新文件
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)
这是来自@Lother的答案的一个“分叉”(我相信这应该被认为是正确的答案)。
对于这样的文件:
$ cat file.txt
1: october rust
2: november rain
3: december snow
Lother解决方案中的这个分支工作得很好:
#!/usr/bin/python3.4
with open("file.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if "snow" not in line:
f.write(line)
f.truncate()
改进:
使用open,丢弃了f.s close()的用法 更清晰的if/else用于计算当前行中是否存在字符串
下面是其他一些从文件中删除/some行的方法:
src_file = zzzz.txt
f = open(src_file, "r")
contents = f.readlines()
f.close()
contents.pop(idx) # remove the line item from list, by line number, starts from 0
f = open(src_file, "w")
contents = "".join(contents)
f.write(contents)
f.close()
我喜欢这个使用fileinput和inplace方法的方法:
import fileinput
for line in fileinput.input(fname, inplace =1):
line = line.strip()
if not 'UnwantedWord' in line:
print(line)
它比其他答案少一点啰嗦而且足够快
您可以使用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)
按行号删除文件中的某一行。
用文件名和要删除的行号替换变量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
你想从文件中删除特定的行,所以使用这个简短的代码片段,你可以很容易地删除任何带有句子或前缀(符号)的行。
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)
推荐文章
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?