我有一个输入文件,如: input.txt中:
to
the
cow
eliphant
pigen
then
enthosiastic
我想删除那些字符长度为< = 4的单词,如果某个单词有超过8个字符,则将这些单词写入新文件中,直到8个字符长度 输出应该像: output.txt的:
eliphant
pigen
enthosia
这是我的代码:
f2 = open('output.txt', 'w+')
x2 = open('input.txt', 'r').readlines()
for y in x2:
if (len(y) <= 4):
y = y.replace(y, '')
f2.write(y)
elif (len(y) > 8):
y = y[0:8]
f2.write(y)
else:
f2.write(y)
f2.close()
print "Done!"
当我编译它然后它给出输出如:
eliphantpigen
then
enthosia
它还写了4个字符长度的单词...我不明白是什么问题以及如何编写代码来限制文本文件字的字符长度....?
答案 0 :(得分:0)
在处理文件时使用with
,这可以保证文件将被关闭。
然后你的结果就是你的阅读线而不是世界。
每行都有结尾'\ n'的符号。因此,当你阅读世界then
时,你会有字符串
'然后\ n'和此字符串的len
为5。
with open('output.txt', 'w+') as ofp, open('input.txt', 'r') as ifp:
for line in ifp:
line = line.strip()
if len(line) > 8:
line = line[:8]
elif len(line) <= 4:
continue
ofp.write(line + '\n')