1

I'm having trouble with some code at the moment, I can't quite figure out how to add the year (last 4 digits of multiple filenames) as a sort of 'ID' field, using a for-loop? I know there are other ways of doing this but I would like to try this way as I'm learning for-loops.

Code I have so far:

import csv

def extract_names(filename):

inF = open(filename, 'rU')
csvF = csv.reader(inFile, delimiter=',')


# Initialization
results = []
rowNum = 0

for row in  csvFile:

    if rowNum != 0:  #no need for first row#

        #This is where the results list is appended #

        records.append((row[0], row[1], "Boy")) 
        records.append((row[2], row[3], "Girl"))  





    rowNum += 1

inF.close()
return(results)



#### Start main program  #####

filenames = ('file2010.csv',     
'file2011.csv',
'file2012.csv', 
'file2013.csv',   
'file2014.csv')

outF = open('fileAll.csv','wb') 
csvF_out = csv.writer(outFile, delimiter=',')

for filename in filenames:
name, ext = filename.split('.')
year = name[-4:]     
results = extract_names(filename)




for line in results:
    line.insert(0,year)

print("Write in csv file...")     

outF.close()

Desired output:

2010 | Y | X | Z
5
  • Where do | Y | X | Z come from? Are they generated from the extract_content function? Are you just looking to append the date from the file name to the result from extract_content? Commented May 22, 2015 at 7:58
  • | X | Y | Z | come from the 'result' list generated earlier Commented May 22, 2015 at 8:00
  • Did I answer your question? If yes then please accept the answer. Commented May 22, 2015 at 9:00
  • The code you gave me messes with my original list. It out puts all my values in a single row of the output csv not as separated fields :/ Commented May 22, 2015 at 9:04
  • Your results are lists of lists, maybe try now Commented May 22, 2015 at 9:25

2 Answers 2

2
import csv
filenames = (
    'file2010.csv',     
    'file2011.csv',
    'file2012.csv', 
    'file2013.csv',
    'file2014.csv'
)

outF = open('fileAll.csv', 'wb') 
csvF_out = csv.writer(outF, delimiter=',')

def extract_content(filename):
    return [("0","1","boy"),("2","3","girl")]

for filename in filenames:
    name, ext = filename.split('.')
    year = name[-4:]     
    result = extract_content(filename)
    for row in result:
        csvF_out.writerow((year,)+row)

outF.close()


#  fileall.csv:
# 2010  | x |   y | z
# 2011  | x |   y | z
# 2012  | x |   y | z
# 2013  | x |   y | z
# 2014  | x |   y | z

Where | represents a new column. Note that instead of using csv.writerowsoutside of the loop, the code uses csv.writerowinside the for-loop. No additional loop is necessary.

Sign up to request clarification or add additional context in comments.

3 Comments

Getting this error: csvF_out.writerow((year)+row) TypeError: cannot concatenate 'str' and 'tuple' object
How do I ever repay you?!?!
dont have enough reputation bro sorry
0

You want to insert the year as the first cell of each line (if I understood correctly. If think that the following is self explained

filenames = ('file2010.csv',
             'file2011.csv',
             'file2012.csv',
             'file2013.csv',
             'file2014.csv')

outF = open('fileAll.csv','wb')
csvF_out = csv.writer(outF, delimiter=',')

for filename in filenames:
    name, ext = filename.split('.')
    year = name[-4:]
    result = extract_content(filename)

    ### Here is the loop you are looking for
    for line in result:      # for each line
        line.insert(0, year) # insert the year as the first cell

    csvF_out.writerows(reult)

outF.close()

Few other notes

  • take a look at with open(file): which is more secure
  • you expect 2010 | Y | X | Z while you delimiter is set to , in your writer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.