如何从输入文件中将每个字母写入文件?

时间:2014-10-13 13:01:34

标签: python python-3.x

def main():
    filename = input('Enter filename: ')
    f = read(filename)
    out_file = input('Enter file: ')
    of = out(out_file)

//我认为代码效率很低,我可以提高效率吗?

for line in f:
   for words in line.split():
      for letter in words:

          if (words.isalpha()): 
             of.write(letter.lower())
    of.write('\n')

2 个答案:

答案 0 :(得分:2)

这将打印文件的每个字母

with open('foo.txt', 'r+') as f:
    a = [l for line in f for l in line if l.isalpha()]
    with open('out_file.txt', 'w') as w:
        for i in a:
            w.write(i.lower()) 

答案 1 :(得分:0)

使用@ vishnu-upadhyay回答并考虑@ vamosnadal123评论:

out = open('out_file.txt', 'w')
_ = [w for line in open('foo.txt', 'r') for w in line if w.isalpha() or w=='\n']
out.close()

编辑: 如果你还想留下你可以写的所有空间,那就更好了:

out = open('out_file.txt', 'w')
_ = [w for line in open('foo.txt', 'r') for w in line if w.isalpha() or w.isspace()]
out.close()

EDIT2对于强化编辑感到抱歉,我认为这是一个更好的解决方案:

out = open('out_file.txt', 'w')
_ = [''.join([w for w in line if w.isalpha()]) + '\n' for line in open('foo.txt', 'r')]
out.close()