如何使用Python在多个CSV文件的末尾添加一个空行

2024-04-19 09:33:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3&我很难将多个csv文件中的行附加到主机的多行中_总计.csv文件。我怀疑这是由于没有一个“预先存在”的空白行为每个csv文件。如果这是真的,我如何添加一个新的空行到每个总计.csv文件?你知道吗

你知道吗总计.csv文件:

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

你知道吗环境.csv文件:

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

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

硕士_总计.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...

硕士_环境.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.")

Tags: 文件csvpathaswithfilesopendirectory
1条回答
网友
1楼 · 发布于 2024-04-19 09:33:27

如果您使用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)

相关问题 更多 >