假設我有一個包含這樣資料的檔案:
Bicycle,204,28,271,193
Bicycle,136,190,79,109
我想將數字相加,這樣新行就會像這樣
Bicycle,204,28,475,221 #as 271 204=475 and 28 193=221
Bicycle,136,190,215,229 #as 136 79=215 and 190 190=229
依此類推,我該怎么做那個筆記我試影像這樣拆分數字:
with open(filepath) as f:
matrix=[line.split(',') for line in f]
f.close()
print(matrix[0])
所以當我列印矩陣時,它給了我這個輸出
['Bicycle', '204', '28', '271', '193\n']
那么如何對數字求和并修改我的檔案以獲取新數字?
uj5u.com熱心網友回復:
# your default code that reads in the csv
with open(filepath) as f:
matrix=[line.split(',') for line in f]
f.close()
# 'w' means to write over the file and its existing content
with open(filepath, 'w') as f:
# loop over each row in your matrix
for row in matrix:
# add 2nd position value in list to 4th
row[3] = int(row[1]) int(row[3])
# values are read in as string, and last value can contain linebreak
row[4] = row[4].replace('\n', '')
# add 2nd position value in list to 4th
row[4] = int(row[2]) int(row[4])
# turn values back into string
row = [str(val) for val in row]
# concatenate into comma separated string
row = ','.join(row)
# write to file
f.write('{}\n'.format(row))
f.close()
uj5u.com熱心網友回復:
with open("bike.txt") as f:
matrix=[line.strip().split(',') for line in f] #add strip to get rid of '\n'
f.close()
newMatrix = [] #setup the new Matrix you'll want to use
for each in matrix:#iterate the initial matrix you took from the txt file
myMatrix = []#new lines that will be added to the newMatrix
myMatrix.append(each.pop(0))#first item that will be kept as a string
addThis = 0 #variable for adding the values
for rest in each:#for everything left after removing the first string
addThis = int(rest) # convert to integer and add to the sum value
myMatrix.append(addThis) # add that summed value to the new line cell
newMatrix.append(myMatrix) #add that line to the total matrix
print(newMatrix[0]) #test that it works
uj5u.com熱心網友回復:
如果你使用背景關系管理器打開一個檔案with,它會在縮進塊的末尾自動關閉,所以不要關閉它!
為了讀取和寫入同一個檔案,您可以創建一個具有兩個功能 enable、open("path", "r ") doc或fileinput模塊doc的描述符;在這里您可以找到更多示例ex。
這里有一個基本的方法:
path = 'my_file' # your path
# read
text = ''
with open(path, 'r') as fd:
text = fd.read()
# process
new_text = ''
for line in text.splitlines():
bike, term1, term2, term3, term4 = line.split(',')
# new relationships
new_term3 = f'{int(term1) int(term3)}'
new_term4 = f'{int(term2) int(term4)}'
# update result
new_text = ','.join((bike, term1, term2, new_term3, new_term4)) '\n'
# save
with open(path, 'w') as fd:
fd.write(new_text)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458896.html
上一篇:自定義檔案輸入按鈕,在div內部按鈕內創建一個不可見的輸入檔案型別用于檔案輸入
下一篇:如何在兩個檔案之間交換整數?
