gpt4 book ai didi

python - 如何使用 Python 在多个 CSV 文件末尾添加空白行

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:22 25 4
gpt4 key购买 nike

我正在使用 Python 3,并且在将多个 csv 文件中的行 append 到 Master_Total.csv 文件的多行中时遇到问题。我怀疑这是由于每个 csv 文件没有“预先存在”的空白行。如果这是真的,如何向每个 TOTAL.csv 文件添加新的空白行?

TOTAL.csv 文件:

GND, 0.1V, 1.0V, REFKelvin,
0.000000, 0.100436, 1.003407, 150318.406250,
[no empty row]

enviro.csv 文件:

temp [C], pressure [kPa], humidity [%RH]
23.870001, 85.903000, 33.75244
[empty row]

当我运行脚本时,我得到:

Master_Total.csv

GND, 0.1V, 1.0V, REFKelvin,
0.000000, 0.100436, 1.003407, 150318.4062500.000000, 0.100764, 1.005011, 100.3399580.000019, 0.100252, 1.002642, 100.214996...

Master_enviro.csv

temp [C], pressure [kPa], humidity [%RH]
23.870001, 85.903000, 33.752441
23.760000, 85.914001, 32.997131
24.040001, 85.879997, 33.134460
...

代码:

import shutil, glob, csv, os, sys



path = r'directory'
Enviro_Files = glob.glob(path +"**/*enviro.csv")
Total_Files = glob.glob(path +"**/*TOTAL.csv")

with open('directory_desktop/Master_enviro.csv', 'wb') as outfile1:
for i, filename1 in enumerate(Enviro_Files):
with open(filename1, 'rb') as inputfile1:
if i != 0:
inputfile1.readline()
shutil.copyfileobj(inputfile1, outfile1)
print(filename1 + " has been imported.")
with open('directory_desktop/Master_TOTAL.csv', 'wb') as outfile2:
for h, filename2 in enumerate(Total_Files):
with open(filename2, 'rb') as inputfile2:
if h != 0:
inputfile2.readline()
shutil.copyfileobj(inputfile2, outfile2)
print(fname2 + " has been imported.")

最佳答案

如果您使用Python的CSV库,您可以轻松测试以确保给定行中有值,这样即使没有空行也没关系,在写入主文件时它们将被跳过:

import csv
import glob

def merge_csvs(target_filename, csv_list):
with open(target_filename, 'w', newline='') as f_master_target:
csv_master_target = csv.writer(f_master_target)
write_header = True

for csv_filename in csv_list:
with open(csv_filename, 'r', newline='') as f_single:
csv_single = csv.reader(f_single)
header = next(csv_single)

if write_header:
csv_master_target.writerow(header)
write_header = False

for row in csv_single:
if row:
csv_master_target.writerow(row)


path = 'directory'
Enviro_Files = glob.glob(path + "**/*enviro.csv")
Total_Files = glob.glob(path + "**/*TOTAL.csv")

merge_csvs('Master_enviro.csv', Enviro_Files)
merge_csvs('Master_TOTAL.csv', Total_Files)

关于python - 如何使用 Python 在多个 CSV 文件末尾添加空白行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48408948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com