Search code examples
pythoncsvlowercase

How to convert contents of csv to lowercase in Python?


I've looked at all the threads I can find but I still can't figure it out, I'm having all sorts of issues.

First issue is that I can't change the items in a list to lower case, so I have to convert it to a string first. Once I do that I can't append strings back into the list without it creating a double list. Why can't I simply change a list to lowercase, delete contents in csv, then paste the lowercase list back in?

My latest attempt, but I've tried many things.

with open(teacherDD, 'r+') as f:
read = csv.reader(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
for row in read:
    copyRow = row.copy()
    # print(copyRow)
    del row[:]
    # print(row)
    getLowerStr = str(copyRow).lower()
    # appendLower = row.append(getLowerStr)
    # print(getLowerStr)
    print(row)
    f.write(getLowerStr)
f.close()

Solution

  • If you just want to convert to lowercase, why use the csv reader?

    You can use the fileinput module to edit lines in place.

    Python3.x

    import fileinput
    
    for line in fileinput.input("test.txt", inplace=1):
        print(line.lower(), end='') 
    

    Python2.x

    import fileinput
    import sys
    
    for line in fileinput.input("test.txt", inplace=1):
        sys.stdout.write(line.lower())
    

    One cool feature of this module is, when you open a file with it, anything that is printed with print or sys.stdout.write is redirected to the file. Sample input:

    UPPER,CASE,ROW
    

    Output:

    upper,case,row