我有一个包含以下文本的文件。我想在python中打开文件,阅读每一行,然后以每行只有40个字符的方式编辑文件。在此行的结尾,我想有一个“ +”号。保存文件。 需要帮助来编写此脚本。
file = "Starting today (September 17), a range of iPhones and iPads are set to change, courtesy iOS 12. Apple has started the rollout of the next version of its mobile operating system called iOS 12. Available as a free upgrade, iOS 12 will make your iPhones and iPads faster, more secure and add a slew of new features including Memphis, Siri shortcuts and grouped notifications. Wonder if your iPhone and iPad is compatible with the all-new iOS 12? Here's the complete list of devices compatible with the new Apple OS."
答案 0 :(得分:1)
这是一种方式:
如果您实际上想拆分单词或其他具有这些功能的单词,它会使用Python's textwrap module将文本“包装”为最多40个字符行。
from textwrap import wrap
# File containing your text.
with open("./Text Document.txt", 'r') as read_file:
data = read_file.read()
data_list = wrap(data, 40)
# New file created with 40 + "+" per line.
with open("./New Text Document.txt", 'w') as write_file:
for data in data_list:
write_file.write(data + "+\n")
这将强制执行40个字符的严格限制:
# File containing your text.
with open("./Text Document.txt", 'r') as read_file:
data = read_file.read()
data_list = []
b, e = 0, 40
while e < len(data):
data_list.append(data[b:e])
b += 40
e += 40
if e > len(data):
data_list.append(data[b:len(data)])
# New file created with 40 + "+" per line.
with open("./New Text Document.txt", 'w') as write_file:
for data in data_list:
write_file.write(data + "+\n")
答案 1 :(得分:0)
file[:40]
将给您前40个字符
还请查看this以获得更多信息