Python:将csv文件的内容添加到列表

时间:2019-05-29 22:43:45

标签: python list csv readfile

对此有一个新问题,我可以通过一些帮助来解决。 就像我将csv(以逗号作为分隔符)传递到列表之前一样。 列表中的第一个元素将始终是整数,而后两个元素将是字符串。 我正在尝试向csv添加新行,该行在第一个元素中将具有递增的编号,但是我还将在其他两个元素中添加哈希字符串。 由于文件为空,因此可以在第一次运行时使用,但是在尝试第二次运行时会收到错误

  

chain_list = [lineList [-1]中的i的int(i).split(',')]

     

ValueError:以10为底的int()的无效文字:'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')

4 个答案:

答案 0 :(得分:0)

尝试一下。

your_list = []
for i in lineList[-1].split(','):
    try:your_list.append(int(i))
    except:your_list.append(i)

答案 1 :(得分:0)

您可以使用csv模块逐行解析CSV内容。只需前进到最后一行,然后丢弃中间数据即可:

import csv

with open('c:\\securelog_workfiles\\chain_info.txt') as data:
    for row in csv.reader(data):  # parse each line to a row
        continue  # skip through the csv row-wise
    last_line_data = row

这适用于任意大文件,因为它只加载单个行,而不是一次加载整个文件。

如果文件很大,并且您想避免解析丢弃的行的开销,请前进到最后一行并仅解析该行。您可以使用next(csv.reader([row]))来分析最后一行,如果格式很简单,也可以使用row.split(...)之类的东西

with open('c:\\securelog_workfiles\\chain_info.txt') as data:
    for row in data:  # do not parse each line
        continue  # skip through the csv row-wise
    last_line_data = row.split(',')  # parse the last line explicitly

答案 2 :(得分:0)

感谢大家的帮助。最终使这块小东西起作用了。文件的第一行(始终为1,0,0)将作为整数传递到名为lineList的列表中。 然后,此列表中第一个值为1的元素将递增并打印到屏幕上。

import os
import io
import sys
import zipfile
import shutil
import csv
from os import path
from zipfile import ZipFile
from shutil import make_archive

#input file
chain_file = 'c:\\securelog_workfiles\\chain_info.txt'

#Check if chain_info.txt exists
chain_file_exists = os.path.isfile(chain_file)
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()
    else:
        #Read the last line of a file
        fileHandle = open (chain_file)
        lineList = fileHandle.readlines()
        fileHandle.close()
        print (lineList)
        print ("The last line is:")
        print (lineList[-1])

        #split the line into separate values using the comma as the delimeter
        chain_list = lineList[-1].split(',')

        #convert the string characters from the file into integers before adding 
        #to the list
        chain_list = [int(i) for i in lineList[-1].split(',')]
        print (chain_list)

        #increment 1 to 2
        increment_value = (chain_list[0])
        increment_value = increment_value +1

        #remove the first element from the list
        chain_list.remove (chain_list[0])
        #verifying that the 1st element was removd
        print (chain_list)

        #insert the incremented value into the list
        chain_list.insert (0,increment_value)
        print('chain list now is: ' + str(chain_list))

else:    
    print ('file does not exist')

答案 3 :(得分:-1)

list1 = []
for ele in line:
   list1.append(ele[0])

list2 = []
for ele in line:
   list2.append(ele[0])

list3 = []
for ele in line:
   list3.append(ele[0])

your_list = []
your_list.append(list1[-1])
your_list.append(list2[-1])
your_list.append(list3[-1])