在Python中组合Regex文件

2024-04-27 04:25:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有48个。接收.txt我正在尝试使用Python将它们组合起来。我知道当你结合的时候。接收.txt文件之间必须包含“|”。你知道吗

下面是我使用的代码:

import glob

read_files = filter(lambda f: f!='final.txt' and f!='result.txt', glob.glob('*.txt'))


with open("REGEXES.rx.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())
            outfile.write('|')

但是当我尝试运行时,我得到了一个错误:

Traceback (most recent call last):
  File "/Users/kosay.jabre/Desktop/Password Assessor/RegexesNEW/CombineFilesCopy.py", line 10, in <module>
    outfile.write('|')
TypeError: a bytes-like object is required, not 'str'

有没有办法把我的文件合并成一个文件?你知道吗


Tags: 文件代码inimporttxtreadaswith
2条回答

您的REGEXES.rx.txt是以二进制模式打开的,但是使用outfile.write('|')您试图向它写入字符串而不是二进制。似乎您的所有文件都包含文本数据,因此不要将其作为二进制文件打开,而是将其作为文本打开,即:

with open("REGEXES.rx.txt", "w") as outfile:
    for f in read_files:
        with open(f, "r") as infile:
            outfile.write(infile.read())
            outfile.write('|')

python2.7.x中,您的代码可以正常工作,但是对于python3.x您应该在字符串outfile.write(b'|')中添加b前缀,该前缀将字符串标记为二进制字符串,然后我们就可以以二进制文件模式编写它了。你知道吗

那么,python3.x的代码将是:

import glob

read_files = filter(lambda f: f!='final.txt' and f!='result.txt', glob.glob('*.txt'))


with open("REGEXES.rx.txt", "wb") as outfile:
    for f in read_files:
        with open(f, "rb") as infile:
            outfile.write(infile.read())
            outfile.write(b'|')

相关问题 更多 >