Python 合并目录中的文件
Python merging files in directory
我在一个目录中有数千个具有这种模式的文件 YYYY/MM/DD/HH/MM:
- 201801010000.txt
- 201801010001.txt
- 201801010002.txt
我只想保留小时数,所以我需要将每天每小时的 60 个文件合并为一个文件。
我不知道如何搜索文件名来获取我想要的 60 个文件。这是我写的
def concat_files(path):
file_list = os.listdir(path)
with open(datetime.datetime.now(), "w") as outfile:
for filename in sorted(file_list):
with open(filename, "r") as infile:
outfile.write(infile.read())
如何命名文件以保留日期?我现在正在使用日期时间,但它会覆盖当前文件名。使用我的代码,我将所有文件合并为一个文件,我应该将每 % 60 合并到一个不同的文件中。
您可以使用 glob
来获取您想要的文件。它允许您传入一个模式以在搜索文件时进行匹配。在下面的最后一行中,它只会查找以 '2018010100'
开头、有两个字符并以 '.txt'
结尾的文件
from glob import glob
def concat_files(dir_path, file_pattern):
file_list = glob(os.path.join(dir_path, file_pattern))
with open(datetime.datetime.now(), "w") as outfile:
for filename in sorted(file_list):
with open(filename, "r") as infile:
outfile.write(infile.read())
concat_files('C:/path/to/directory', '2018010100??.txt')
你并没有那么远,你只需要交换你的逻辑:
file_list = os.listdir(path)
for filename in sorted(file_list):
out_filename = filename[:-6] + '.txt'
with open(out_filename, 'a') as outfile:
with open(path + '/' + filename, 'r') as infile:
outfile.write(infile.read())
试试这个。
file_list = os.listdir(path)
for f in { f[:-6] for f in file_list }:
if not f:
continue
with open(f + '.txt', 'a') as outfile:
for file in sorted([ s for s in file_list if s.startswith(f)]):
with open(path + '/' + file, 'r') as infile:
outfile.write(infile.read())
#os.remove(path + '/' + file) # optional
我在一个目录中有数千个具有这种模式的文件 YYYY/MM/DD/HH/MM:
- 201801010000.txt
- 201801010001.txt
- 201801010002.txt
我只想保留小时数,所以我需要将每天每小时的 60 个文件合并为一个文件。 我不知道如何搜索文件名来获取我想要的 60 个文件。这是我写的
def concat_files(path):
file_list = os.listdir(path)
with open(datetime.datetime.now(), "w") as outfile:
for filename in sorted(file_list):
with open(filename, "r") as infile:
outfile.write(infile.read())
如何命名文件以保留日期?我现在正在使用日期时间,但它会覆盖当前文件名。使用我的代码,我将所有文件合并为一个文件,我应该将每 % 60 合并到一个不同的文件中。
您可以使用 glob
来获取您想要的文件。它允许您传入一个模式以在搜索文件时进行匹配。在下面的最后一行中,它只会查找以 '2018010100'
开头、有两个字符并以 '.txt'
from glob import glob
def concat_files(dir_path, file_pattern):
file_list = glob(os.path.join(dir_path, file_pattern))
with open(datetime.datetime.now(), "w") as outfile:
for filename in sorted(file_list):
with open(filename, "r") as infile:
outfile.write(infile.read())
concat_files('C:/path/to/directory', '2018010100??.txt')
你并没有那么远,你只需要交换你的逻辑:
file_list = os.listdir(path)
for filename in sorted(file_list):
out_filename = filename[:-6] + '.txt'
with open(out_filename, 'a') as outfile:
with open(path + '/' + filename, 'r') as infile:
outfile.write(infile.read())
试试这个。
file_list = os.listdir(path)
for f in { f[:-6] for f in file_list }:
if not f:
continue
with open(f + '.txt', 'a') as outfile:
for file in sorted([ s for s in file_list if s.startswith(f)]):
with open(path + '/' + file, 'r') as infile:
outfile.write(infile.read())
#os.remove(path + '/' + file) # optional