sizz sizz - 3 months ago 11
Python Question

Change all text in file to lowercase

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.

Answer

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