3

我有一个包含一堆文本的文件,我想撕掉它,匹配一堆东西,然后将这些项目写入新文件中的单独行。

这是我整理的代码的基础知识:

f = open('this.txt', 'r')
g = open('that.txt', 'w')
text = f.read()
matches = re.findall('', text) # do some re matching here
for i in matches:
    a = i[0] + '\n'
    g.write(a)
f.close()
g.close()

我的问题是我希望每个匹配的项目都在一个新行上(因此是 '\n'),但我不希望文件末尾有一个空行。

我想我不需要文件中的最后一项被换行符尾随。

解决这个问题的 Pythonic 方式是什么?另外,我在代码中设置它的方式是最好的方式,还是最 Pythonic 的方式?

4

1 回答 1

6

如果您想写出一系列行,它们之间有换行符,但最后没有换行符,我会使用str.join. 也就是说,用这个替换你的 for 循环:

output = "\n".join(i[0] for i in matches)
g.write(output)

为了避免必须显式关闭文件,特别是如果您的代码可能被异常中断,您可以使用该with语句使事情变得更简单。以下代码替换了您问题中的整个代码:

with open('this.txt') as f, open('that.txt', 'w') as g:
    text = f.read()
    matches = re.findall('', text) # do some re matching here
    g.write("\n".join(i[0] for i in matches))

或者,因为您不需要同时打开两个文件:

with open('this.txt') as f:
    text = f.read()
matches = re.findall('', text) # do some re matching here
with open('that.txt', 'w') as g:
    g.write("\n".join(i[0] for i in matches))
于 2012-11-11T09:05:48.773 回答