我有一段文本,我想在少于50个字符的任何行的末尾添加一个换行符。
这是我在的地方
text = open('file.txt','r+')
line_length = []
lines = list(enumerate(text))
for i in lines:
line_length.append(len(i))
print lines
print line_length
我最终得到了一堆又一遍的2值。我知道每行的长度不是2。
编辑:这是我使用的解决方案
text = open('text.txt','r+')
new = open('new.txt','r+')
new.truncate(0)
l=[]
for i in text.readlines():
if len(i) < 50:
l.append(i+'\n')
else:
l.append(i)
new.write(' '.join(l))
text.close()
new.close()
答案 0 :(得分:2)
像:
text = open('file.txt','r+')
l=[]
for i in text.readlines():
if len(i)<50:
l.append(i)
else:
l.append(i.rstrip())
不需要enumerate
。
或者是单线(我推荐这样做):
l=[i if len(i)<50 else i.rstrip() for i in text.readlines()]
因此,由于enumerate
的原因,您的代码无法正常工作。
两种情况:
print(l)
是所需的输出。
答案 1 :(得分:0)
line 8 [radius = float(input("Input Radius: "))]
是对的列表(每个长度为2)。您需要检查子列表的长度,而不是它所在的对:
lines
尽管如您所见,您没有使用for i, seq in lines:
line_length.append(len(seq))
,所以使用i
没有意义。
答案 2 :(得分:0)
假设您要写入新文件,则需要这样的内容:
with open("file.txt", "r+") as input_file, open("output.txt", "w") as output_file:
for line in input_file:
if len(line) < 50:
line += '\n'
output_file.write(line)
现有文件中的行通常已经在它们的末尾添加了换行符,因此对于长度小于50的行,结果将是两个换行符。如果需要避免使用rstrip
。