2 回答

TA貢獻1772條經驗 獲得超6個贊
我在下面寫了這段代碼只是為了讓你知道如何去做。請注意,下面的代碼不會檢查任何錯誤。如果您的 CSV 文件之一為空,如果找不到該文件,并且您定義的列是其中一個文件中的不存在列,則其行為未定義??赡苓€有更多。因此,您需要圍繞它構建一個檢查代碼。此外,您的 CSV 格式可能很大程度上取決于 python csv 包。
所以現(xiàn)在到代碼解釋。對于“路徑”變量。你可以給它一個字符串、一個元組或一個列表。如果您給它一個字符串,它會將其轉換為具有一個索引的元組。您可以為該變量提供要使用的文件。
對于“列”變量,該變量應該是一個字符串。如果需要,您需要為此構建錯誤檢查。
對于代碼例程,該函數(shù)將讀取路徑列表的所有 CSV 文件。每次讀取文件時,都會先讀取第一行并將內容保存到變量(rowFields)中。
之后,它生成帶有鍵(列名)到值(位置)的dict標頭(字段)。該字典用于通過使用其名稱來搜索列位置。在這里,您還可以瀏覽每個字段,如果該字段與列名匹配,則將該值保存為列位置。然后可以稍后使用該位置,而不是繼續(xù)使用該名稱在字典中搜索該位置。本段中描述的后一種方法應該是最快的。
之后,它會繼續(xù)讀取 CSV 文件的每一行,直到最后。每次讀取一行時,它都會檢查“column”變量定義的列中字符串的長度是否大于零。如果該字符串長度大于零,那么它將將該行附加到變量 contentRows。
函數(shù)讀取完 CSV 文件后,會將變量“rowFields”和“contentRows”的內容寫入由“outfile”變量定義的 CSV 文件。為了方便我,outfile 簡單地等于輸入文件+“.new”。你可以改變它。
import csv
def getNoneEmpty( paths, column ):
if isinstance(paths, str):
paths = (paths, )
if not isinstance(paths, list) and not isinstance(paths, tuple):
raise("paths have to be a or string, list, or tuple")
quotechar='"'
delimiter=","
lineterminator="\n"
for f in paths:
outfile = f + ".new" # change this area to how you want to generate the new file
fields = {}
rowFields = None
contentRows = []
with open(f, newline='') as csvfile:
csvReader = csv.reader(csvfile, delimiter=delimiter, quotechar=quotechar, lineterminator=lineterminator)
rowFields = next(csvReader)
for i in range(0, len(rowFields)):
fields[rowFields[i]] = i
for row in csvReader:
if len(row[fields[column]]) != 0:
contentRows.append(row)
with open(outfile, 'w') as csvfile:
csvWriter = csv.writer(csvfile,delimiter=delimiter, quotechar=quotechar,quoting=csv.QUOTE_MINIMAL, lineterminator=lineterminator)
csvWriter.writerow(rowFields)
csvWriter.writerows(contentRows)
getNoneEmpty(["test.csv","test2.csv"], "1958")
test.csv 內容:
"Month","1958","1959","1960"
"JAN",115,360,417
"FEB",318,342,391
"MAR",362,406,419
"APR",348,396,461
"MAY",11,420,472
"JUN",124,472,535
"JUL",158,548,622
"AUG",505,559,606
"SEP",404,463,508
"OCT",,407,461
"NOV",310,362,390
"DEC",110,405,432
test2.csv 內容:
"Month","1958","1959","1960"
"JAN",,360,417
"FEB",318,342,391
"MAR",362,406,419
"APR",348,396,461
"MAY",,420,472
"JUN",,472,535
"JUL",,548,622
"AUG",505,559,606
"SEP",404,463,508
"OCT",,407,461
"NOV",310,362,390
"DEC",110,405,432

TA貢獻1848條經驗 獲得超6個贊
希望它會起作用:
def main():
temp = []
with open(r'old_csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=';')
for row in csv_reader:
for x in row:
temp.append(x)
with open(r'new_csv', mode='w') as new_file:
writer = csv.writer(new_file, delimiter=',', lineterminator='\n')
for col in temp:
list_ = col.split(',')
writer.writerow(list_)
添加回答
舉報