在python

时间:2017-09-30 10:18:46

标签: 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”的文件夹,而numers 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()

谢谢!

1 个答案:

答案 0 :(得分:0)

如果要将新条目添加为列而不是向下添加行,则每次都必须读入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中的内置函数,因此您不应该将该名称用作变量,因为代码中可能会发生意外情况。