![](/img/trans.png)
[英]Taking output calculated from data in multiple text files and writing them into different columns of a CSV file
[英]Python- Taking columns from multiple .csv files and paste them into new .csv master file
所以這就是問題,我有4個.csv文件,我要從這4個文件中的每一個復制一個列,並將它們合並為一個新的.csv主文件的第一列。 然后,使用另一組不同的列再次重復相同的過程,並將其存儲為主文件的第二列,然后再執行至少12次。
到目前為止,這是我的代碼:
碼-
import os
import csv
import datetime as dt
from os import listdir
from os.path import join
import matplotlib.pyplot as plt
#get the list of files in mypath and store in a list
mypath = 'C:/Users/Alan Cedeno/Desktop/Test_Folder/'
onlycsv = [f for f in listdir(mypath) if '.csv' in f]
#print out all the files with it's corresponding index
for i in range(len(onlycsv)):
print(i,onlycsv[i])
#prompt the user to select the files
option = input('please select file1 by number: ')
option2 = input('please select file2 by number: ')
#build out the full paths of the files and open them
fullpath1 = join(mypath, onlycsv[option])
fullpath2 = join(mypath, onlycsv[option2])
#create third new.csv file
root, ext = os.path.splitext(fullpath2)
output = root + '-new.csv'
with open(fullpath1) as r1, open(fullpath2) as r2, open(output, 'a') as w:
writer = csv.writer(w)
merge_from = csv.reader(r1)
merge_to = csv.reader(r2)
# skip 3 lines of headers
for _ in range(3):
next(merge_from)
for _ in range(1):
next(merge_to)
for merge_from_row, merge_to_row in zip(merge_from, merge_to):
# insert from col 0 as to col 0
merge_to_row.insert(1, merge_from_row[2])
# replace from col 1 with to col 3
#merge_to_row[0] = merge_from_row[2]
# delete merge_to rows 5,6,7 completely
#del merge_to_row[5:8]
writer.writerow(merge_to_row)
有什么建議么?
請讓我知道帖子是否需要格式化。
您想在這里做什么? 如果您想將所有csv合並為原樣,那就很好了。
with open(fullpath1) as r1, open(fullpath2) as r2, open(output, 'a') as fout:
for line in r1:
fout.write(line)
for line in r2:
fout.write(line)
fout.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.