したがって、私のファイルはまったく同じサイズで、行ヘッダーと列ヘッダーがあります。行と列のヘッダー以外の残りのセルにある値を追加する必要があります。これは私がそれを行うために使用している関数です:
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) までの範囲は完璧です。
何か案は?