将结果写入.txt文件

2024-05-16 04:11:08 发布

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

我创建了一个代码来获取两个.txt文件,比较它们并将结果导出到另一个.txt文件。下面是我的代码(抱歉搞砸了)。你知道吗

有什么想法吗?还是我只是个白痴?你知道吗

使用python 3.5.2:

# Barcodes Search (V3actual)

# Import the text files, putting them into arrays/lists

with open('Barcodes1000', 'r') as f:
    barcodes = {line.strip() for line in f}

with open('EANstaging1000', 'r') as f:
    EAN_staging = {line.strip() for line in f}

##diff = barcodes ^ EAN_staging 
##print (diff)



in_barcodes_but_not_in_EAN_staging = barcodes.difference(EAN_staging)

print (in_barcodes_but_not_in_EAN_staging)

# Exporting in_barcodes_but_not_in_EAN_staging to a .txt file

with open("BarcodesSearch29_06_16", "wt") as BarcodesSearch29_06_16:    # Create .txt file
    BarcodesSearch29_06_16.write(in_barcodes_but_not_in_EAN_staging)    # Write results to the .txt file

Tags: 文件代码intxtaswithlinenot
2条回答

试试BarcodesSearch29_06_16.write(str(in_barcodes_but_not_in_EAN_staging))。另外,在用BarcodesSearch29_06_16.close()完成对文件的写入之后,您还需要关闭该文件。你知道吗

从您的问题的注释来看,您的问题似乎是希望将字符串列表保存为一个文件。File.write需要一个字符串作为输入,而File.writelines需要一个字符串列表,这就是您的数据。你知道吗

with open("BarcodesSearch29_06_16", "wt") as BarcodesSearch29_06_16:
    BarcodesSearch29_06_16.writelines(in_barcodes_but_not_in_EAN_staging)

它将遍历列表in_barcodes_but_not_in_EAN_staging,并将每个元素作为单独的行写入文件BarcodesSearch29_06_16。你知道吗

相关问题 更多 >