所以我的文件大小完全相同,有一个行标题和一个列标题。除了行和列标题之外,我需要添加其余单元格中的值。这是我用来做的功能:
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:\...\..\...\文件 2.csv')
文件完全相同。我在它们的 C 位置打开文件并使用另存为将它们保存到我的 python 文件夹中。但是,当我访问 C 文件夹中的文件时,我的 1 到 len(row1) 的范围超出了范围。
当我从我的 python 文件夹访问相同的文件时,我的 1 到 len(row1) 的范围是完美的。
有任何想法吗?