python读取一个txt文件 使其变成每行20个字符的形式?
比如一个txt文件:test1内容是abcdefghijklmnopqrstabcdefghijklmnopqrstopq
def test1_linelength(input_file,20)
使输出为:
abcdefghijklmnopqrst
abcdefghijklmnopqrst
opq 展开
如何让python把从txt文件中读入的文字按20个字符一行的形式分隔开呢。大概的思路是,先读入文件所有字符,然后使用range生成[0,20,40,...]的列表以供索引,然后用这个索引,生成有关于该字符串的新列表[s[0:20],s[20:40],...],若不专门去除换行符,代码用这个思路就够了,可以这么写(以下13行就是)(限于python3):
#-*-coding:utf-8;-*-
f=open("test.txt","w")
print("abcdefghijklmnopqrstabcd"
"efghijklmnopqrstopq",file=f)
f.close()
#生成待读入文件
#再从待读入文件中读入处理
f=open("test.txt","r")
s=f.read()
l=len(s)
b=(list(range(0,l,20)))
p=[s[i:i+20] for i in b]
r=[print(i) for i in p]
请问假如分隔的每一行以,结尾该怎么操作呢?
请问假如导入的是函数 使其可以变成每行50个字符应该怎样写呢?
def test1_linelength(input_file,length)
print(test1_linelength(f,50))
#-*-coding:utf-8;-*-
import os;
import os.path;
s=("""ALICE was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, "and what is the use of a book," thought Alice, "without pictures or conversations?"
"""
).replace("\n"," ").replace(" "," ");
def consistentlinelength(filename, length):
script_dir = os.path.dirname(os.path.abspath(__file__));
input_file = os.path.join(script_dir, "test_data", filename);
print(input_file);
f=open(input_file,"r")
s=f.read()
l=len(s)
b=(list(range(0,l,length)))
p=[s[i:i+length] for i in b]
r=[print(i) for i in p]
return s
script_dir = os.path.dirname(os.path.abspath(__file__));
os.chdir(script_dir)
if not os.path.exists("test_data"):(
os.mkdir("test_data"));pass;
f=open("test_data/test1.txt","w")
print(os.path.abspath("test_data/test1.txt"))
print(s,file=f)
f.close()
#生成待读入文件
#再从待读入文件中读入处理
print(
consistentlinelength("test1.txt", 50));
"""
就差文本环绕没有解决,输出的单词在行尾会断到下一行
"""