Python 将两个列表压缩到文本文件中

Python 将两个列表压缩到文本文件中,python,arraylist,Python,Arraylist,我正在尝试创建一个程序来代替Excel创建CSV(供个人使用)。但是,下面的代码复制了第一个文本文件中的值。例如,我拥有的第一个文本文件是“sourcecasnumbers” 当它打开拉链时,会产生以下结果 1099221909922 当它应该执行以下操作时: 71751412,阿维菌素 这是我的密码: import os import csv import time #----Federal/State----# #Ask the user to fill out a text file w

我正在尝试创建一个程序来代替Excel创建CSV(供个人使用)。但是,下面的代码复制了第一个文本文件中的值。例如,我拥有的第一个文本文件是“sourcecasnumbers”

当它打开拉链时,会产生以下结果
1099221909922

当它应该执行以下操作时:
71751412,阿维菌素

这是我的密码:

import os import csv import time

#----Federal/State----#
#Ask the user to fill out a text file with Source CAS numbers
print("Input the source CAS numbers with which you're comparing against")
os.system("notepad.exe C:\sourcecas.txt")
time.sleep(15)

#Take the text file with Source CAS Numbers and make it into a list
sourcecas = []
file = open(r'C:\sourcecas.txt', 'r')
sourcecas = file.readlines()
sourcecas[:] = [line.rstrip('\n') for line in sourcecas]

#Ask the user to fill out a text file with Source CAS names
print("Input the source CAS names in alphabetical order")
os.system("notepad.exe C:\sourcecasnames.txt")
time.sleep(15)

#Take the text file with Source CAS Names and make it into a list
sourcecasnames = []
file = open(r'C:\sourcecas.txt', 'r')
sourcecasnames = file.readlines()
sourcecasnames[:] = [line.rstrip('\n') for line in sourcecasnames]

#Zip the source cas numbers and names into a CSV file
zip(sourcecas, sourcecasnames)
with open(r'C:\CAS-S.csv', 'w') as f:
writer = csv.writer(f, delimiter=',')
writer.writerows(zip(sourcecas, sourcecasnames))

我把它删减了一点,但这是我编辑过的代码。整个问题是您没有关闭名称文件

import csv

fnumbers = r'casnum.txt'
fnames = r'casname.txt'
foutput = r'CAS-S.csv'
#Take the text file with Source CAS Numbers and make it into a list
sourcecas = []
file = open(fnumbers, 'r')
sourcecas = file.readlines()
sourcecas[:] = [line.rstrip('\n') for line in sourcecas]
file.close() # Here's the fix

#Take the text file with Source CAS Names and make it into a list
sourcecasnames = []
file = open(fnames, 'r')
sourcecasnames = file.readlines()
sourcecasnames[:] = [line.rstrip('\n') for line in sourcecasnames]
file.close() # Make sure to close your file when you're done with it

#Zip the source cas numbers and names into a CSV file
zip(sourcecas, sourcecasnames)
with open(foutput, 'w') as f: # note that with open() closes itself
    writer = csv.writer(f, delimiter=',')
    writer.writerows(zip(sourcecas, sourcecasnames))
之后,我得到了CAS-S.csv,其中包含:

71751412,Abamectin
83329,Acenaphthene
...
10026116,Zirconium tetrachloride

你能提供一些样本数据的要点吗这些是CAS编号,如果你愿意的话,这些是化学名称。这是一个坏习惯。谢谢你的简单修复。不用担心,我建议在所有情况下都使用带有open()的
作为f
习惯用法。这是一个很好的python习语,可以减少打字和潜在的错误。