如果有一个文本文件,其中每行可能有不同的长度,那么如何将文件的每一行格式化为长度为一定数量的字符?
例如,转动
>Letters of the alphabet
ABCDEFGHIJKLMNOPQRSTUVWXYZ
到
>Letters of the alphabet
ABCDE
FGHIJ
KLMNO
PQRST
UVWXY
Z
等等。
答案 0 :(得分:0)
在python 3中:
# -*- coding: utf-8 -*-
max_length = int(input("Max length of your line = "))
file = open("file.txt","r") #open the file to edit and read the data
content = file.read()
file.close()
file_out = open("file_out.txt","w+") #create the output file
for i in range(len(content)):
file_out.write(content[i])
if (i + 1) % max_length == 0: #add line break each time pgcd equal 0
file_out.write('\n')
file_out.close()