簡體   English   中英

將日期列添加到python中的附加輸出csv文件

[英]adding date column to the appending output csv file in python

我在下面使用此代碼合並所有csv文件:每個文件下面有10,000行:

billing_report_2014-02-01.csv billing_report_2014-02-02.csv:

fout=open("out.csv","a")
for num in range(1,10):
    print num
    for line in open("billing_report_2014-02-0"+str(num)+".csv"):
         fout.write(line) 
for num in range(10,29):
    print num
    for line in open("billing_report_2014-02-"+str(num)+".csv"):
         fout.write(line) 
fout.close()

但是現在我想向out.csv文件中添加新的日期列,如何添加日期列並將值“ 2014-02-01”添加到將billing_report_2014-02-01附加到out.csv的每一行中,並賦值我將billing_report_2014-02-02附加到out.csv的每一行中的“ 2014-02-02”的問題,我該如何處理?

列出您要使用的文件名,然后從中獲取數據,在輸入文件上構建一個生成器,以刪除尾隨的新行,並添加一個帶有日期的新字段...例如:

filenames = [
  'billing_report_2014-02-01.csv',
  'billing_report_2014-02-02.csv'
]

with open('out.csv', 'w') as fout:
    for filename in filenames:
        to_append = filename.rpartition('_')[2].partition('.')[0]
        with open(filename) as fin:
            fout.writelines('{},{}\n'.format(line.rstrip(),to_append) for line in fin)

我認為您可以在末尾添加日期:

for line in open("billing_report_2014-02-0"+str(num)+".csv"):
     fout.write(line+',DATE INFORMATION') 

我假設您的CSV確實是逗號分隔的,如果分開制表符,則字符應為\\ t

您還可以通過更改以下行來使用中間步驟:

line = line + ', DATE INFORMATION'

當您嘗試添加文件名日期時,只需將其添加到每個變量中即可:

line = line + ', 2014-02-0'+ str(num//10)

您可以使用replace函數(如果它始終是“,LLC”字符串表達式),請參見下面的示例

>>> string = "100, 90101, California, Example company,LLC, other data"
>>> string.replace(',LLC',';LLC')
'100, 90101, California, Example company;LLC, other data'
>>> 

將所有內容放在一起,並嘗試從@Jon CLements中引入一些靈感(KUDOS!):

def combine_and_add_date(year, month, startday, endday, replace_dict):
    fout=open("out.csv","a")
    for num in range(startday,endday+1):
        daynum = str(num)
        if len(daynum) ==1:
            daynum = '0'+daynum

        date_info = str(year+'-'month+'-'+daynum)
        source_name = 'billing_report_'+date_info+'.csv'

        for line in open(source_name):
            for key in replace_dict:
                line.replace(key,replact_dict[key])

            fout.write(line+','+date_info) 

    fout.close()

我希望它能奏效,並且您應該(希望我是新手...)像這樣使用它,請注意,該詞典旨在允許您進行各種替換

combine_and_add_date("2014","02",1,28, {',LLC': ';LLC', ',PLC':';PLC'}) 

手指交叉

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM