【发布时间】:2022-01-23 06:25:33
【问题描述】:
例如,我有两个文件 .txt。 第一个文件有 78 行,第二个文件有 30 行。 有没有简单的方法将数字作为参数传递给结果? 目前我得到的结果:
first_file_20.txt
first_file_40.txt
first_file_60.txt
first_file_80.txt
second_file_20.txt
second_file_40.txt
但我想有这样的结果:
first_file_1.txt
first_file_2.txt
first_file_3.txt
first_file_4.txt
second_file_1.txt
second_file_2.txt
代码:
import re
import os
lines_per_file = 20
smallfile = None
root_path = os.getcwd()
if os.path.exists(root_path):
files = []
for name in os.listdir(root_path):
if os.path.isfile(os.path.join(root_path,name)):
files.append(os.path.join(root_path,name))
print(files) #list all files in directory
for ii in files:
if ii.endswith(".txt"): # only txt files
with open(ii,'r') as bigfile:
name1 = str(os.path.basename(ii).split(".")[0])
name2 = str(name1 + '_{}.txt')
#
print('name', name2)
for lineno, line in enumerate(bigfile):
w = 1
if lineno % lines_per_file == 0:
if smallfile:
smallfile.close()
small_filename = name2.format(lineno + lines_per_file)
smallfile = open(small_filename, "w")
smallfile.write(line)
if smallfile:
smallfile.close()
谁能帮帮我?
【问题讨论】:
-
为什么文件中的行数与此处相关?
-
您是否要重命名文件?这只是为了展示目的吗?你知道你要迭代的文件名是否总是有相同的前缀吗?
-
文件名总是有相同的前缀
-
我想把大文件分成小文件,以便以后用正则表达式处理
-
所以所有
first_file_N.txt都是first_file.txt的块?你知道你可以使用 Unixsplit命令来做到这一点,不是吗?
标签: python python-3.x