简体   繁体   中英

Couldn't create csv file and copy data from another in python

This code takes a word from ss file and matches all the entries in the 1 file and then pick them and create a file containing those entries and the name of file would be the keyword. But there is problem with the looping or something I am not getting it.It creates a file without any name suppose 1.csv contains certain data with xyz and we pass xyz keyword from the ss.csv file and matches with all the entries and picking them out the entire row and printing them in another csv file.

 import csv
#opening the first file to read
first_file = open('1.csv')
first_var = csv.reader(first_file)

#creating list to append the values
new_values = []
old_values = []

#reading all the keyword from the external csv file
varia_3 = []
strng_conv=''
varia_1 = ''
external_keyw_file = open('ss.csv')
external_keyw_ob = csv.reader(external_keyw_file)


#extracting all the rows from keywords passed
#loop
for i in external_keyw_ob:
    varia_2=i
    strng_conv = ''.join(map(str,varia_2))
    print "%s\n"%strng_conv
    varia_1 = strng_conv+'.csv'
    print varia_1
    for row in first_var:
        if  strng_conv in row[2]:
            new_values.append(row)
        else:
            old_values.append(row)

    second_file = open(varia_1, 'wb')
    second_ob = csv.writer(second_file, dialect = 'excel')
    second_ob.writerows(new_values)
    third_file = open('2.csv', 'wb')
    third_ob =csv.writer(third_file, dialect='excel')
    third_ob.writerows(old_values)
    fir_file = open('2.csv','wb')
    first_var =csv.reader(fir_file)
#opening third file after removing all the entries from the keywords passed in varia

It looks like you are expecting just creating the reader to do the reading for you - you need to actually tell it to do the read at some point with external_keyw_ob.readrows() , to get your keywords. Try using a debugger or adding some print statements to make sure you have the content you are expecting.

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