簡體   English   中英

如何格式化文本文件中所有行的長度

[英]How to format the length of all lines in a text file

如果存在一個文本文件,其中每一行的長度可能不同,那么如何將文件的每一行的格式設置為一定數量的字符?

例如,轉

>Letters of the alphabet
ABCDEFGHIJKLMNOPQRSTUVWXYZ

>Letters of the alphabet
ABCDE
FGHIJ
KLMNO
PQRST
UVWXY
Z

依此類推。

在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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM