我有大約60個CSV,每個都有4個公共值,我需要將其提取並轉換爲一個CSV。我在這裏刪除了很多信息,但確認'output_contents'具有所有正確的信息,但是當我調用'create_csv'時,它不會被寫入。將列表的列表寫入CSV,但只能獲取密鑰
def create_csv(list_of_lists):
'''
Writes the list of lists to a actual CSV file.
PARAMS:
list_of_lists - A list of keys, and each key is a list of values.
RETURNS: None.
OUTPUTS: A CSV file named "output.csv".
'''
print "Attempting to write CSV."
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(list_of_lists.keys())
print "Write successful."
fileList = get_all_files(csv_directory)
get_csv_contents(fileList)
# Copy over the columns from the contents dictionary.
wanted_columns = ["key1", "key2", "key2", "key4",]
# Creates a key: value pair for every key and value in content as long as the key is a wanted column.
output_contents = {key: value for key, value in content.items() if key in wanted_columns}
create_csv(output_contents)
我已確認output_contents包含來自應該輸入CSV的所有信息。
當我運行此,我output.csv樣子:
k,e,y,1
k,e,y,2
k,e,y,3
k,e,y,4
我知道我在什麼地方做一些小的,愚蠢的錯誤,但認爲我的大腦是油炸和想不通的地方呃是。
編輯:
這是可運行的代碼。
import csv
def create_csv(list_of_lists):
'''
Writes the list of lists to a actual CSV file.
PARAMS:
list_of_lists - A list of keys, and each key is a list of values.
RETURNS: None.
OUTPUTS: A CSV file named "output.csv".
'''
print "Attempting to write CSV."
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(list_of_lists.keys())
print "Write successful."
output_contents = {
'key1': ["k1v1","k1v2","k1v3"],
'key2': ["k2v1","k2v2","k2v3"],
'key3': ["k3v1","k3v2","k3v3"],
'key4': ["k4v1","k4v2","k4v3"],}
create_csv(output_contents)
也許你可以把我們可以複製,粘貼並找到問題的工作代碼:) – cdonts