【发布时间】:2019-05-29 22:43:44
【问题描述】:
对此有一个新问题,我可以通过一些帮助来解决。 就像在我将 csv(以逗号作为分隔符)传递到列表中之前一样。 列表中的第一个元素将始终是整数,但接下来的两个将是字符串。 我正在尝试向 csv 添加一个新行,该行将在第一个元素中增加一个数字,但我还将在其他两个元素中添加哈希字符串。 它在第一次运行时有效,因为文件为空,但是当它尝试第二次运行时出现错误
chain_list = [int(i) for i in lineList[-1].split(',')]
ValueError: int() 以 10 为底的无效文字:'9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794'
我传入的文件的第一行包含:
1,0,9891b18cf04418b92c0ee611201da47ef00471090aebdfa6667097d81d0832cb2edab83f65a4dc497fbffc4332d7e794
我的代码现在看起来像这样。不知道如何解决这个问题?
#Check if chain_info.txt exists
CHAIN_FILE_exists = os.path.isfile(CHAIN_FILE)
#If chainfile is empty set element 0 in list to 1
if CHAIN_FILE_exists:
if os.stat(CHAIN_FILE).st_size == 0:
print('empty')
fileHandle = open (CHAIN_FILE, 'a')
fileHandle.write('1,0,0')
fileHandle.close()
fileHandle = open (CHAIN_FILE)
lineList = fileHandle.readlines()
fileHandle.close()
chain_list = lineList[-1].split(',')
chain_list = [int(i) for i in lineList[-1].split(',')]
increment_value = 1
print('1 chain list now is: ' + str(chain_list))
else:
#Read the last line of a file
fileHandle = open (CHAIN_FILE)
lineList = fileHandle.readlines()
fileHandle.close()
#Take last line of file and add to a list called chain_list
chain_list = lineList[-1].split(',')
chain_list = [int(i) for i in lineList[-1].split(',')]
#increment the first value in the list by 1, this will be used to determine the block number
increment_value = (chain_list[0])
increment_value = increment_value +1
chain_list.remove (chain_list[0])
chain_list.insert (0,increment_value)
print('chain list now is: ' + str(chain_list))
#Open file
fileHandle = open (CHAIN_FILE, 'a')
#Write the contents of the list to the chain file on a new line and separate with a comma
fileHandle.write('\n' + str(chain_list[0]) + ',' + str(chain_list[1]))
fileHandle.close()
else:
print ('file does not exist')
【问题讨论】:
-
csv文件的分隔符是什么? -
它只是一个逗号