python批量删除csv文件首行
方法一:批量删除csv文件首行
# -*- encoding: utf-8 -*-
"""
@Author: Little duo
@Time: 2023/2/27 21:51
@Contact: 1049041957@qq.com
@License: (C)Copyright 2021-2022, Little duo
"""
import fileinput
import os
path = r'D:\csv_files'
files = os.listdir(path)
files = tuple([os.path.join(path, file) for file in files])
with fileinput.input(files=files, backup='.bak', inplace=True) as f:
for line in f:
if not fileinput.isfirstline():
print(line.replace('\n', ''))
在上面的代码中
fileinput.input() 函数支持传入多个文件名
inplace 参数指定直接在文件中进行修改(后面的print函数输出内容便是修改后的内容)
backup 参数指定在修改之前备份文件,备份文件的扩展名为 .bak
fileinput.isfirstline() 函数判断当前行是否是文件的第一行,如果不是,则打印内容
需要注意的是,使用 fileinput 模块修改文件时,如果程序中断或者出现异常,可能会导致文件被破坏,因此,在修改文件之前最好备份原始文件,以防止数据丢失。
方法二:批量删除csv文件首行
# -*- encoding: utf-8 -*-
"""
@Author: Little duo
@Time: 2023/2/27 21:51
@Contact: 1049041957@qq.com
@License: (C)Copyright 2021-2022, Little duo
"""
import os
source_folder = 'source_csv_files'
target_folder = 'target_csv_files'
os.makedirs(source_folder, exist_ok=True)
os.makedirs(source_folder, exist_ok=True)
source_files_path = os.path.join(os.getcwd(), source_folder)
target_files_path = os.path.join(os.getcwd(), target_folder)
source_files_name_list = os.listdir(source_files_path)
files_path_list = tuple([[os.path.join(source_files_path, file), os.path.join(target_files_path, file)] for file in source_files_name_list])
for files_path in files_path_list:
source_file_name = files_path[0]
target_file_name = files_path[1]
with open(source_file_name, mode='r', encoding='utf-8') as source_file, open(target_file_name, mode='w', encoding='utf-8') as target_file:
lines = source_file.readlines()[1:]
target_file.writelines(lines)
source_file.close()
target_file.close()
print(f'{source_file_name} 处理完毕!')