访问位于Python文件夹外的CSV文件
我的文件大小完全一样,都有行标题和列标题。我需要把除了行标题和列标题之外的所有单元格里的值加起来。这是我用来实现这个功能的代码:
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()
这个代码运行得很好。不过,file1和file2不在我的python文件夹里。我需要用的代码是 data = readStructured('C:\...\..\...\file1.csv') data2 = readStructured('C:\...\..\...\file2.csv')
这两个文件完全相同。我在C盘的位置打开了这些文件,然后用“另存为”把它们保存到了我的python文件夹里。但是,当我从C盘访问这些文件时,我的范围从1到len(row1)就超出了范围。
而当我从我的python文件夹访问同样的文件时,范围从1到len(row1)就完全正常。
有什么想法吗?
1 个回答
0
这些文件是完全一样的。我在它们的C盘位置打开了文件,然后用“另存为”把它们保存到了我的Python文件夹里。
我觉得这可能会导致一些看不见的转换问题。比如说,可能会添加一个文件结束符,或者去掉最后的换行符之类的。我不会相信这些文件是完全一样的,除非你直接复制文件。