2016-08-12 43 views
0
from itertools import chain 
from glob import glob 

file = open('FortInventory.txt','w') 

lines = [line.lower() for line in lines] 
with open('FortInventory.txt', 'w') as out: 
    out.writelines(sorted(lines)) 

我想将txt文件中的所有文本转换为小写如何执行此操作,这里是我迄今为止的代码,并且我查看了堆栈上的一些问题溢出,但我无法完全弄清楚,如果有人可以将我链接到正确的文章或告诉我什么是我的代码错误,我将不胜感激。将文件中的所有文本更改为小写

+3

要开始,你永远不迭代的实际文件。应该是“lines = [line.lower()for line in file]” – Enders

+0

ahhhh duhhhhhh,哑巴我谢谢你! – goldenwest

回答

1

两个问题:

  1. 打开与'r'读文件。
  2. lines更改为file在您的列表中的理解。

这里的固定代码:

from itertools import chain 
from glob import glob 

file = open('FortInventory.txt', 'r') 

lines = [line.lower() for line in file] 
with open('FortInventory.txt', 'w') as out: 
    out.writelines(sorted(lines)) 
+1

打开文件'r +'然后寻求开始覆盖所有内容并使用最外面的'with open(...)as file:' – oldrinb

+1

https://stackoverflow.com/questions/6648493/open-file-for-both-reading-and-writing解释@oldrinb在说什么 – Enders

+1

我同意。也许这是meta的一个问题,但我试图只改变原始代码中所要求或需要的内容,以便区分只是样式更改/优化和实际解决问题的区别。我很高兴这些评论在这里虽然指向进一步的代码改进:) – Karin

相关问题