簡體   English   中英

從多個csv文件中提取行和文件名

[英]extract rows and filenames from multiple csv files

我在文件夾中有多個日期為文件名(20080101.csv至20111031.csv)的csv文件。 csv文件具有公共頭。 csv文件如下所示:

20080101.csv  
X ;Y; Z  
1 ; 1 ; 3  
1 ; 2 ; 6  
1 ; 3 ; 24  
2 ; 1 ; 24  
2 ; 2 ; 24  

20080102.csv   
X ;Y; Z  
1 ; 1 ; 0.1  
1 ; 2 ; 2  
1 ; 3 ; 67  
2 ; 1 ; 24  
2 ; 2 ; 24  

20080103.csv  
X ;Y; Z  
1 ; 1 ; 3  
1 ; 3 ; 24  
2 ; 1 ; 24  
2 ; 2 ; 24  

20080104.csv   
X ;Y; Z  
1 ; 1 ; 34  
1 ; 2 ; 23  
1 ; 3 ; 67  
2 ; 1 ; 24  
2 ; 2 ; 24  

… 等等。 我想編寫一個腳本來讀取行,如果在給定行中我們有X = 1和Y = 2,則將整個行與文件名一起復制到新的csv文件中,並提供以下輸出:

X ;Y ; Z ; filename  
1  ; 2 ; 6 ; 20080101  
1  ; 2 ; 2 ; 20080102  
1  ; 2 ; NA; 20080103  
1  ; 2 ; 23; 20080104 

關於如何完成此操作的任何想法,以及我應該研究的有關模塊的任何建議或任何示例。 感謝您的時間和幫助。

干杯,納文

這是一個格式正確的問題,邏輯應該從中顯而易見。 為某人提供完成的代碼會破壞分配的目的。 首先,在問題中添加“作業”標簽,然后考慮要做什么:1)循環遍歷文件(跟蹤每個文件名的打開狀態)2)從當前文件中讀取行3)如果選擇滿足條件(x == 1和y == 2),然后寫一行。

要開始使用,請嘗試:

import csv, os

for fn in os.listdir():
    if ".csv" in fn:
        with open(fn, 'r', newline='') as f:
            reader = csv.reader(f, delimiter=";")
            for row in reader:
                ...

然后擴展解決方案以打開輸出文件,並使用csv.writer寫入選定的行。

您可以一次讀入每個文件。 逐行閱讀

files = ['20080101.csv', '20080102.csv', '20080103.csv'] #...etc
for f in files:
    file = open(f, 'r')
    for line in file:
        ray = line.split(';')
        if (ray[0].strip() == '1' and ray[1].strip() == '2'):
            fout = open('output.csv', 'a')
            fout.write(ray[0].strip() + ' ; ' + ray[1].strip() + ' ; ' + ray[2].strip() + ' ; ' + f + '\n')
            fout.close()
    file.close()

經過測試和工作。 可能需要稍作修改。

這應該可以完成以下工作:

import glob
import os

outfile = open('output.csv', 'w')
outfile.write('X ; Y ; Z ; filename\n')
for filename in glob.glob('*.csv'):
  if filename == 'output.csv': # Skip the file we're writing.
    continue
  with open(filename, 'r') as infile:
    count = 0 
    lineno = 0 
    for line in infile:
      lineno += 1
      if lineno == 1: # Skip the header line.
        continue
      fields = line.split(';')
      x = int(fields[0])
      y = int(fields[1])
      z = float(fields[2])
      if x == 1 and y == 2:
        outfile.write('%d ; %d ; %g ; %s\n' % (x, y, z, filename))
        count += 1
    if count == 0: # Handle the case when no lines were found.
      outfile.write('1 ; 2 ; NA ; %s\n' % filename)
outfile.close()

請注意,如果您無法控制或信任文件格式,則可能要處理由轉換為int / float引發的異常。

如果您知道每天都有一個文件,沒有丟失的日子,那么我會使用glob('*。csv')來獲取文件名列表,再開一個,然后像泰勒所做的那樣閱讀

如果您知道有文件丟失的日子,我將使用datetime與datetime.date(2008,1,1)一起顯示,並循環增加一天。 然后我每天都使用.strftime()+'.csv'撰寫文件名,然后嘗試處理文件(如果沒有文件,只需用NA寫一個重新編碼)

以下應該工作:

import csv
with open('output.csv', 'w') as outfile:
    outfile.write('X ; Y ; Z ; filename\n')
    fmt = '1 ; 2 ; %s ; %s\n'
    files = ['20080101.csv', '20080102.csv', '20080103.csv', '20080104.csv']
    for file in files:
        with open(file) as f:
            reader = csv.reader(f, delimiter=';')
            for row in reader:
                if len(row) > 2 and row[0].strip() == '1' and row[1].strip() == '2':
                    outfile.write(fmt % (row[2].strip(), file[:-4]))
                    break
            else:
                outfile.write(fmt % ('NA', file[:-4]))

暫無
暫無

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

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