简体   繁体   中英

Large text file: Fails to convert one character into another in python

I'm pretty new to Python and want to convert one character into another character in a large string .txt file.

I tried running the following code on shell:

#Takes text in letter and converts it
old_text = open("letter.txt", "r")

#Convert old_text to new_text replacing all instances of "a" or into "u"
new_text = old_text.upper().replace("a", "u")
print new_text

However, it returns the error "NameError: name 'old_text' is not defined"

Is there anything else I should do to fix this or am I missing something big here?

First off, open() returns a file handle; you need to read the file from the handle if you want a string.

Then you're upper casing the whole string and searching for a lower case letter, which will never replace anything.

Unless there's part of your code that isn't here, it's unclear to me what's resulting in that error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM