Python: добавление содержимого CSV-файла в список - PullRequest
0 голосов
/ 30 мая 2019

есть новая проблема, с которой я мог бы справиться.Как и прежде, я передаю CSV (с запятой в качестве разделителя) в список.первый элемент в списке всегда будет целым числом, но следующие два будут строками.Я пытаюсь добавить новую строку в CSV, который будет иметь увеличенное число в первом элементе, но я также добавлю строки хеша в двух других элементах.Он работает при первом запуске, поскольку файл пуст, но при попытке второго запуска я получаю сообщение об ошибке

chain_list = [int (i) для i в lineList [-1] .split ('')]

1005 * 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')

Ответы [ 4 ]

0 голосов
/ 30 мая 2019

Спасибо всем за помощь.В конце концов этот маленький кусочек заработал.Первая строка файла, которая всегда равна 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')
0 голосов
/ 30 мая 2019
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])
0 голосов
/ 30 мая 2019

Вы можете использовать модуль 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
0 голосов
/ 30 мая 2019

Попробуйте это.

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