所以我的文件大小完全相同,带有行标题和列标题。我需要在除行和列标题之外的其余单元格中添加值。这是我用来做的功能:
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文件夹访问SAME文件时,我的范围是1到len(row1) 完善。
有什么想法吗?
答案 0 :(得分:0)
文件完全相同。我在他们的C位置打开文件并使用save将它们保存到我的python文件夹中。
听起来我觉得这可能是一些无形转换的源头。添加文件结尾字符,或删除尾随换行符或类似内容。除非你复制文件,否则我不相信文件是相同的。