目前我有一个代码可以将一堆键值对写入 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
#Gets the time in integer format
intnow = int(timeteller())
#Goes back as many days as you would like, comment out to get yesterday
#intnow -= 1
#turns back to string
now = str(intnow)
thelist = []
#opens the banumbers list
thispath = open('banumberlist4.txt')
finallist = []
#counter to see what number it's on
counter = 0
#loop to iterate through each ba number
for files in thispath:
getem = files
banumber = getem[0:8]
print(banumber)
#combines each ba number with the date and time to match transaction report format
combined = '{}_{}'.format(banumber,now)
thepaths = these_files(banumber, combined)
needtomakepretty = get_odometers(thepaths)
goeslast = make_pretty(needtomakepretty)
finallist.append(goeslast)
counter+=1
print(counter)
#writes to txt file in dictionary(key value pair (json)) format
f = open ('c:\\users\\me\\desktop\\versionstest.csv', 'w')
for ba in finallist:
sba = str(ba)
f.write('{}\n'.format(ba))
#f.write(',')
最后结果是这样的:
{'02105': ' (5.10)'}
基本上,我想将 02105 号码与 5.10 分开,并将它们放在单独的列中。有什么建议吗?
最佳答案
csv通常使用一些分隔符:','(逗号)、' '(空格)、'\t'(制表符)等。
所以你必须使用“,”作为分隔符而不是“_”
combined = '{}_{}'.format(banumber,now)
关于python - 写入 csv,每个项目位于单独的列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52426360/