gpt4 book ai didi

python - 拆分命令 - 选择输出名称

转载 作者:太空宇宙 更新时间:2023-11-04 10:30:54 25 4
gpt4 key购买 nike

我有一个名为 myfile.txt 的文本文件。该文件包含 50,000 行,我想将其拆分为 50 个文本文件。我知道使用 split 命令很容易:

split myfile.txt

这将输出 50 个 1000 行的文件:xaa、xab 和 xac。

我的问题是,如何运行拆分文本文件以便命名输出文件:

1.txt 
2.txt
3.txt

...

50.txt

请用 python 或 bash 寻求答案。谢谢你!

最佳答案

这是一个使用 itertools.islice 的潜在解决方案获取不同文件名的 block 和字符串格式:

from itertools import islice

with open('myfile.txt') as in_file:
for i in range(1, 51):
with open('{0}.txt'.format(i), 'w') as out_file:
lines = islice(in_file, 1000)
out_file.writelines(lines)

关于python - 拆分命令 - 选择输出名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26722872/

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