【问题标题】:Python: Add contents of a csv file to a listPython:将 csv 文件的内容添加到列表中
【发布时间】: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 文件的分隔符是什么?
  • 它只是一个逗号

标签: python list csv readfile


【解决方案1】:

您可以使用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】:

    试试这个。

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

    【讨论】:

    • 如果它解决了您的问题,请您接受并支持答案。 :-)
    • 只是一个后续问题。该文件将包含数字,但当它们被添加到列表中时,它们似乎是字符串。如何将它们作为整数添加到列表中?
    • 干杯,这有效,但现在面临另一个相关问题。会尝试解决这个问题。
    【解决方案3】:

    感谢大家的帮助。最终让这个小块工作。始终为 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')
    

    【讨论】:

      【解决方案4】:
      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])
      

      【讨论】:

      • 嗨!由于篇幅和内容,您的答案出现在审核队列中。像这样的帖子被标记为低质量,因为在 StackOverflow 上通常不鼓励仅代码回答。请为您的答案添加解释。谢谢!
      • 对此感到抱歉.. 在代码中添加了更多 cmets 以解释它应该做什么,并为答案添加了更多解释。
      猜你喜欢
      • 2019-10-14
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多