Question

I have a textfile on my desktop called 'TEXTFILE.docx', in the text file it reads 'Hello my name is Jimmy Jones'. I basically want to call this text file up into python so i can apply some functions that i have made (One that removes vowels and replaces it with blank spaces - and another one that doubles each character [i.e input = the, returns = tthhee])

def withoutVowels(string):
    for vowel in ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]:
        string = string.replace(vowel, " ")
    return string

Above is the function that removes vowels and replaces it with empty spaces.

def doubleChar(doubleit):
    doubled = []
    for letter in doubleit:
        doubled.append(letter*2)
    return "".join(doubled)

Above is my function that doubles the letter

textfile = open('TEXTFILE.docx', 'w')

Above is how i have attempted to open the textfile.

I then tried printing the textfile and this came up: *<_io.TextIOWrapper name='TEXTFILE.docx' mode='r' encoding='US-ASCII'>* Is it possible to assign whatever is in the TEXTFILE to a variable??

Also, i thought perhaps the problem i was having is because python can't call up "Word Document Files" but i looked for a program that used .txt files but i couldn't fund a program on my mac that would use .txt files.

Was it helpful?

Solution

Your problem is that you actually don't have a text file, you have a Microsoft Word file. You need to open the file in Word and chose File->Save As..., and save it as a "Plain Text" file.

OTHER TIPS

When you're opening the textfile, what are your overall intentions? Do you intend to just read the file? Or do you want to both read the file and change it? If you're just reading, open the file with:

textfile = open("textfile.txt","r") #instead of "w," use "r" for reading. "r+" is both.
#Then, go on to read the string
text = str(textfile.read()) #str() is not necessary, but it can't hurt
#Now, the variable "text" is a big string - it contains whatever was in that text file. 
#Then, you can apply your function to it. 
print withoutVowels(text)
print doubleChar(text)

EDIT: The above answer is also correct - you have to copy and paste everything from the Word file into a .txt file (something like Notepad) for the program to work.

Yes, what you want to do is this:

textfile.read()

You see, the textfile is a "file-like" object that supports a bunch of interesting methods. Read up more here: https://docs.python.org/2/library/stdtypes.html#file-objects

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top