简体   繁体   中英

Reading a csv file in python and creating database

I'm working on a function where I need to accept a CSV file name as a string, open and read it, create a database, and then return the database. The attempt I have so far seems to have the correct logic but it is giving me the error "No such file or directory 'filename.csv'. The files I'm reading are called file0.csv, file1.csv, etc. I'll include an example of one of them with my code below. Does anyone have any advice on how to fix this? Thanks

Edit: I realize that what I included below is an example of the database. Apparantly the first line of the file is the header row and the code I have now is reading the header row when it shouldn't be. Here is the updated code below

Code:

def read_file(filename):
    thefile = open(filename)
    data = []
    for line in thefile: 
        data.append(line)
    thefile.close()

    return data



    Example database:

{'Leonardo  da  Vinci': [('Mona Lisa', 1503,    
76.8, 53.0, 'oil paint', 'France'), ('The   
Last Supper', 1495, 460.0, 880.0, 'tempera',    
'Italy')]}

Let's look at just the first two lines of your code:

def read_file(filename):
    thefile = open('filename.csv')

I surmise that, since you want to be able to process more than one file with this code you want to be able to call read_file substituting various filenames in place of filename . Correct?

OK, then one flaw in the code is that filename in the first line is a variable but 'filename.csv' is a literal. This means that no matter what you put for filename in the first line it will NOT change the literal. To do that the second line would have to be, for instance,

thefile = open ('%s.csv' % filename, 'r')

This would put what's in the filename variable in place of the %s and do what you seem to want.

What most respondents are yammering about: Your script (ie, the Python code) might be in one disc folder or directory but the files you want to process might be in a different folder or directory. When you run a script without telling it where to look for files it will assume that you mean in the folder where it's running. At your stage of the game, the easiest thing to do is to put the Python script and the files it needs all in the same folder, and then run then in that same folder.

Maybe you want something like this? It opens your file (provided you find its correct location), accumulates its lines and returns the set of lines in your file.

def read_file(filename):
    thefile = open('file0.csv', 'r')
    lines = []
    for line in thefile: 
        lines.append(line)
    thefile.close()

    return lines

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