3
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))

I am trying to convert all text in a txt file to lowercase how would i go about doing this, here is the code i have so far and i looked at some questions on stack overflow but i couldnt quite figure it out, if anyone could link me to the right article or tell me what is wrong with my code i would greatly appreciate it.

GoldenWest
  • 281
  • 2
  • 4
  • 16

1 Answers1

3

Two problems:

  1. Open the file with 'r' for read.
  2. Change lines to file in your list comprehension.

Here's the fixed code:

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))
Karin
  • 8,404
  • 25
  • 34
  • 1
    it would make more sense to open the file `r+` and then seek to the beginning to overwrite everything and use an outermost `with open(...) as file:` – obataku Aug 12 '16 at 02:40
  • 1
    https://stackoverflow.com/questions/6648493/open-file-for-both-reading-and-writing Explains what @oldrinb is saying – Guillaume Aug 12 '16 at 02:42
  • 1
    I agree. Maybe this is a question for meta, but I try to only change what's asked for or needed from original code so that it's easier to distinguish between what was just a styling change/optimization and what actually fixed problems. I'm glad these comments are here though to point to further code improvements :) – Karin Aug 12 '16 at 02:46
  • Awesome Thank you everyone! you all just saved me hours of work! I seriously LOVE YOU – GoldenWest Aug 12 '16 at 02:49
  • 1
    @sizz why are you using `sorted` exactly? – obataku Aug 12 '16 at 02:50
  • 1
    @Enders thanks; the only points I'd make are that `truncate` is unnecessary here as we're overwriting the entire file anyway and of course we'd do something like `lines = [line.lower() for line in f]; f.seek(0); f.writelines(lines)` – obataku Aug 12 '16 at 02:59
  • @oldrinb was the only example i could find online lol for chaning a text file to lowercase what would the better option? – GoldenWest Aug 12 '16 at 03:06
  • 1
    @sizz you can just use `writelines(lines)` without the `sorted` to keep the original line order – obataku Aug 12 '16 at 03:07
  • ahhhh o i see the sorted did happen to have a good touch to it ! – GoldenWest Aug 12 '16 at 03:09