Python 从txt文件中删除结束于xyz的行

Python 从txt文件中删除结束于xyz的行,python,python-3.x,Python,Python 3.x,我试图编写一个python代码来检查.txt文件中的每一行,如果该行以a/或Z/结尾,则删除该行。这是我写的,请帮我继续写下去 f = open('test.txt', 'r') for line in f.readlines(): if (line.endswith("A/") or line.endswith("Z/")): Remove that line in test.txt 把所有的线都接过来。在所需的写行和写行中打开相同的文件- f = open('fil

我试图编写一个python代码来检查.txt文件中的每一行,如果该行以a/或Z/结尾,则删除该行。这是我写的,请帮我继续写下去

f = open('test.txt', 'r')
for line in f.readlines():
    if (line.endswith("A/") or line.endswith("Z/")):
        Remove that line in test.txt

把所有的线都接过来。在所需的写行和写行中打开相同的文件-

f = open('file.txt', 'r')
lines = f.readlines()
f.close()
f = open('file.txt', 'w')
for line in lines:
    if not line.endswith(("A/", "Z/")):
        f.write(line)
f.close()

把所有的线都接过来。在所需的写行和写行中打开相同的文件-

f = open('file.txt', 'r')
lines = f.readlines()
f.close()
f = open('file.txt', 'w')
for line in lines:
    if not line.endswith(("A/", "Z/")):
        f.write(line)
f.close()

您可以首先打开文件并将行保留在列表中,列表中的行不会以
a/
Z/
结尾:

keep = []
with open('test.txt') as in_file:
    for line in in_file:
        # store in temporary variable to not disrupt original line
        temp = line.rstrip() 
        if not temp.endswith('A/') and not temp.endswith('Z/'):
            keep.append(line)
之后,您可以将此列表中的行写入同一文件:

with open('test.txt', 'w') as out:
    for line in keep:
        out.write(line)

注意:由于文件中的行可能在末尾带有
\r
oe
\n
字符,因此您可以使用。这是必需的,因为像
A/\n
这样的字符串将在
str.endswith('A/')
上失败

您可以首先打开文件,并将行保留在列表中,列表中的行不会以
a/
Z/
结尾:

keep = []
with open('test.txt') as in_file:
    for line in in_file:
        # store in temporary variable to not disrupt original line
        temp = line.rstrip() 
        if not temp.endswith('A/') and not temp.endswith('Z/'):
            keep.append(line)
之后,您可以将此列表中的行写入同一文件:

with open('test.txt', 'w') as out:
    for line in keep:
        out.write(line)

注意:由于文件中的行可能在末尾带有
\r
oe
\n
字符,因此您可以使用。这是必需的,因为像
A/\n
这样的字符串将在
str.endswith('A/')
上失败

您不能写入正在读取的同一文件。因此,将其写入新文件,然后将新文件重命名为旧文件

另外,
将以
\n
\r\n
结尾。因此,用(“A/”检查
line.endswith总是会失败。所以最好使用基于正则表达式的检查

import re
import os
with open('test.txt', 'r') as in_file:
    with open('test2.txt', 'w') as out_file:
        for line in in_file.readlines():
            if re.search(r'[AZ]/[\r\n]+', line):
                continue
            out_file.write(line)

os.rename('test2.txt', 'test.txt')

您不能写入正在读取的同一文件。因此,将其写入新文件,然后将新文件重命名为旧文件

另外,
将以
\n
\r\n
结尾。因此,用(“A/”
检查
line.endswith总是会失败。所以最好使用基于正则表达式的检查

import re
import os
with open('test.txt', 'r') as in_file:
    with open('test2.txt', 'w') as out_file:
        for line in in_file.readlines():
            if re.search(r'[AZ]/[\r\n]+', line):
                continue
            out_file.write(line)

os.rename('test2.txt', 'test.txt')

当然,当同时打开同一文件时,您不能只读取和编辑该文件。
相反,您可以读取、存储内容、修改内容并重新写入同一文件,而无需打开新文件或再次打开同一文件

import re
new_lines = []
with open('sample.txt', 'r+') as f:
    lines = f.readlines()
     for i, line in enumerate(lines):
         if not re.search(r'[AZ]/[\r\n]+', line):
             new_lines.append(line)           # store the content 
    f.truncate(0)     # empty file
    f.seek(0)         
    for line in new_lines:
        f.write(line)   # write into same file

当然,当同时打开同一文件时,您不能只读取和编辑该文件。
相反,您可以读取、存储内容、修改内容并重新写入同一文件,而无需打开新文件或再次打开同一文件

import re
new_lines = []
with open('sample.txt', 'r+') as f:
    lines = f.readlines()
     for i, line in enumerate(lines):
         if not re.search(r'[AZ]/[\r\n]+', line):
             new_lines.append(line)           # store the content 
    f.truncate(0)     # empty file
    f.seek(0)         
    for line in new_lines:
        f.write(line)   # write into same file

你不能从文件中“删除”行,所以最好考虑一个替代方案。你不能从文件中“删除”行,所以最好考虑一个替代方案。你不能这样写和读,这里的
应该是
。你可以。在投票否决我的答案之前,你为什么不试试呢?关于
你是对的,但是说你不能这样写和读是错误的。+1因为没有使用正则表达式
str.endswith
接受要测试的字符串元组,因此如果不是line.endswith((“a/”,“Z/”):
@MatthewStory(可能)暗示的是打开一个文件而从不关闭它可能是不安全的。您重新使用
f
作为下一个操作的文件句柄,因此打开的文件的句柄将丢失,您无法再关闭它。因此,您的操作系统保持“打开”;但显然,它并不介意随后被另一个文件覆盖。有些操作系统并没有那么粗心。使用更具Pythonic的
,缩进将为您显示文件的生存期。您不能这样写和读,这里的
应该是
。您可以。在投票否决我的答案之前,你为什么不试试呢?关于
你是对的,但是说你不能这样写和读是错误的。+1因为没有使用正则表达式
str.endswith
接受要测试的字符串元组,因此如果不是line.endswith((“a/”,“Z/”):
@MatthewStory(可能)暗示的是打开一个文件而从不关闭它可能是不安全的。您重新使用
f
作为下一个操作的文件句柄,因此打开的文件的句柄将丢失,您无法再关闭它。因此,您的操作系统保持“打开”;但显然,它并不介意随后被另一个文件覆盖。有些操作系统并没有那么粗心。使用更具Pythonic风格的
,缩进将为您显示文件生存期。如果您对我的回答满意,请接受答案。我不知道如何做。我是新来的。如果你对我的回答满意,请接受我的回答。我不知道怎么做。我是新来的。你能指引我吗?