简体   繁体   中英

Zip two lists into text file

I'm trying to create a program to replace Excel in creating CSV's (for personal use). The below code, however, duplicates the values from whatever is in the first text file. For example, the first text file I have is "SourceCAS Numbers".

When it zips it produces the following 109922, 109922

When it should be doing the following: 71751412, Abamectin

Here's my code:

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))

I've trimmed it down a bit, but here's my edited code. The whole issue was that you were not closing the names file

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))

Afterward, I have CAS-S.csv containing:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM