猿问

用单独的列中的每个项目写入 csv

目前我有一个代码可以将一堆键值对写入 csv。但是,它将所有内容都放在同一列中。我想将值与键分开以使其更具可读性。这将是很多信息,所以我想让它尽可能地可读。这是我的代码:


import glob

from pathlib import Path

import datetime

import re

import csv





#Gets the current time and returns it in ddmmyyyy format to match Transaction log file names


def timeteller():

    now = datetime.datetime.now()

    month = str('{:02d}'.format(now.month))

    day1 = now.day 

    day =  str('{:02d}'.format(day1))

    year =str(now.year)

    time =year+month+day

    return time


#Folder location for G4S unit transaction reports


def these_files(x, y):

    thislist = []

    configfiles = Path('O:/Unit Management/Reports/G4S/').glob('{}*/{}*Transaction.txt'.format(x, y))


    for files in configfiles:

        thislist.append(files)


    return thislist


#Checks to make sure the date and ba numbers are numbers only


def hasNumbers(inputString):

    numberfinal = []

    numberfinal = re.findall("[.0-9]", inputString)

    if numberfinal == []:

        numberfinal = '1'

    return numberfinal


#Selects which transaction reports to get the data from.  

#Transaction logs that have no date return nothing


def get_odometers(thesepath):

    get_this = []


    for thispath in thesepath:


        with open(thispath,"r") as f:

            searchlines = f.readlines()

        for i, line in enumerate(searchlines):

            if "StartDay" in line:

                get_this.append(line)




    return get_this


##Gets odometer numbers based on string match.  Puts each number in key value pair

#Serial Number added to key value pair


def make_pretty(checkthis):

    the_numbers = {}

    #the_numbers[''] = banumber

    for i, line in enumerate(checkthis):

        #the_numbers['Serial'] = banumber

        if 'StartDay' in line:

            for l in checkthis[i:i+1]: 

                numbers = l[59:67]

                #numberschecked = hasNumbers(numbers)

                the_numbers[banumber] = numbers




    return the_numbers


最后出来是这样的:


{'02105': '  (5.10)'}

基本上我想将 02105 编号与 5.10 分开,并将它们放在单独的列中。有什么建议吗?


四季花海
浏览 114回答 1
1回答

慕哥6287543

csv 通常使用一些分隔符:','(逗号)、' '(空格)、'\t'(制表符)等。所以你必须使用 ',' 作为分隔符而不是 '_'combined = '{}_{}'.format(banumber,now)
随时随地看视频慕课网APP

相关分类

Python
我要回答