开发者

Accessing a CSV File outside python folder

So my files are the exact same size, with a row header and a column header. I need to add the values thare are in the rest of the cells besides the row and column header. This is the function I am using to do it:

def readStructured (filename):

    # Open the file
    fd = open (filename, 'rb')

    # CSV reader
    reader = csv.reader (fd , delimiter = ',')

    # Read data into memory
    data = []
    for row in reader:
        data.append (row)

    return data

def mergeStructured (data1, data2):

    # Empty array
    ret = []

    # Append the row header
    ret.append (data1[0])

    # For rows which are _not_ the row header,
    for rowIndex in range (1, len (data1)):
        row1 = data1[rowIndex]
        row2 = data2[rowIndex]

        # The row we are working on:
        current = []

        # Append the column header
        current.append (row1[0])

        # Now append the sum of the rest of the values
        for index in range (1, len(row1)):
            current.append (float (row1[index]) + float (row2[index]))

        # And put the result in our data
        ret.append (current)

    return ret

    And then I use this to call the functions:


data = readStructured('file1.csv')
data2 = readStructured('file2.csv')
y = mergeStructured(data, data2)
targetfile = open('testing.csv', 'wb')
writer = csv.writer(targetfile)
for row in y:
    writer.writerow(row)
targetfile.close()

This works perfectly. However, file1 and file2 are not in the python folder. The code I need to use is data = readStructured('C开发者_Go百科:\...\..\...\file1.csv') data2 = readStructured('C:\...\..\...\file2.csv')

The files are the exact same. I opened the files in their C location and used save as to save them into my python folder. However, when I access the files in my C folder, my range for 1 to len(row1) goes out of range.

When I access the SAME files from my python folder, my range for 1 to len(row1) is perfect.

Any ideas?


The files are the exact same. I opened the files in their C location and used save as to save them into my python folder.

It sounds to me like this might be the source of some invisible conversion. Adding an end-of-file character, or removing a trailing newline or something like that. I wouldn't trust that the files are the same unless you copy the file.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜