[英]appending dates by columns in a csv file in python
我有一个脚本,它遍历给定路径('C:\\ Users \\ Razvi \\ Desktop \\ italia')中的所有文件,并从名称为“ cnt.csv”的每个文件中读取行数,然后写入在另一个名为“ counters.csv”的文件中,当前日期+文件夹名称+在“ cnt.csv”中找到的行总和。
现在输出文件(“ counters.csv”)如下所示:
30/9/2017
8dg5 5
8dg7 7
01/10/2017
8dg5 8
8dg7 10
其中名称8dg5和8dg7是脚本在其中找到文件“ cnt.csv”的文件夹,数字5、7、8、10是每次我运行脚本时在csv文件中找到的行总和,并且显然我运行脚本的日期,每次都会附加。
现在我想要的是在csv中写那些日期,以某种方式附加在列而不是行上,如下所示:
30/9/2017 01/10/2017
8dg5 5 8dg5 8
8dg7 7 8dg7 10
这是代码:
import re
import os
from datetime import datetime
#italia =r'C:\Users\timraion\Desktop\italia'
italia =r'C:\Users\Razvi\Desktop\italia'
file = open(r'C:\Users\Razvi\Desktop\counters.csv', 'a')
now=datetime.now()
dd=str(now.day)
mm=str(now.month)
yyyy=str(now.year)
date=(dd + "/" + mm + "/" + yyyy)
file.write(date + '\n')
for filename in os.listdir(italia):
infilename = os.path.join(italia, filename)
for files in os.listdir(infilename):
if files.endswith("cnt.csv"):
result=os.path.join(infilename,"cnt.csv")
print(result)
infilename2 = os.path.join(infilename, files)
lines = 0
for line in open(infilename2):
lines += 1
file = open(r'C:\Users\Razvi\Desktop\counters.csv', 'a')
file.write(str(filename) +","+ str(lines)+"\n" )
file.close()
谢谢!
如果要将新条目添加为列而不是下一行,则每次都必须读入counters.csv
文件,追加列并重写。
import os
from datetime import datetime
import csv
italia =r'C:\Users\Razvi\Desktop\italia'
counts = []
for filename in os.listdir(italia):
infilename = os.path.join(italia, filename)
for files in os.listdir(infilename):
if files.endswith("cnt.csv"):
result=os.path.join(infilename,"cnt.csv")
print(result)
infilename2 = os.path.join(infilename, files)
lines = 0
for line in open(infilename2):
lines += 1
counts.append((filename, lines)) # save the filename and count for later
if os.path.exists(r'C:\Users\Razvi\Desktop\counters.csv'):
with open(r'C:\Users\Razvi\Desktop\counters.csv', 'r') as csvfile:
counters = [row for row in csv.reader(csvfile)] # read the csv file
else:
counters = [[]]
now=datetime.now()
# Add the date and a blank cell to the first row
counters[0].append('{}/{}/{}'.format(now.day, now.month, now.year))
counters[0].append('')
for i, count in enumerate(counts):
if i + 1 == len(counters): # check if we need to add a row
counters.append(['']*(len(counters[0])-2))
while len(counters[i+1]) < len(counters[0]) - 2:
counters[i+1].append('') # ensure there are enough columns in the row we're on
counters[i+1].extend(count) # Add the count info as two new cells
with open(r'C:\Users\Razvi\Desktop\counters.csv', 'w') as csvfile:
writer = csv.writer(csvfile) # write the new csv file
for row in counters:
writer.writerow(row)
另一个要注意的是, file
是Python中的内置函数,因此您不应使用该名称作为变量,因为在代码中可能会发生意料之外的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.