我有一个文本文件,可以说FileA.txt。我想每25行分割一次该txt文件,因此第0-25行将是File1.txt,第26-50行将是File2.txt,依此类推。
我试图遵循:
Splitting large text file into smaller text files by line numbers using Python
但是运气不好。我的python技能很基础且很底层。
当我运行它时,出现以下错误:
“”,第1行SyntaxError:(unicode错误)“ unicodeescape”编解码器无法解码位置2-3中的字节:截断的\ UXXXXXXXX转义
然后我用open(r'C:\ Users添加了一个r,现在我得到PermissionError:[Errno 13]权限被拒绝:'C:\ Users \ joker \ Desktop \ LiveStream_Videos'
答案 0 :(得分:2)
您可以尝试每25行分块,然后将它们分别写到单独的文件中
def chunks(l, n):
"""Chunks iterable into n sized chunks"""
for i in range(0, len(l), n):
yield l[i:i + n]
# Collect all lines, without loading whole file into memory
lines = []
with open('FileA.txt') as main_file:
for line in main_file:
lines.append(line)
# Write each group of lines to separate files
for i, group in enumerate(chunks(lines, n=25), start=1):
with open('File%d.txt' % i, mode="w") as out_file:
for line in group:
out_file.write(line)
注意:来自How do you split a list into evenly sized chunks?的分块配方。