1

I am currently trying to learn python to automate some stuff for my classes (I will still manually check until I'm fully confident in my code). In case it is relevant, I am running Ubuntu 18.04 on a Lenovo E430 ThinkPad and an Intel i5-2450M. My python version is Python 3.6 since that is what came with my Ubuntu install and it worked with all my previous testing.

So I am doing some test runs with file i/o. My goal for this code is to count the number of vowels in a passed text file (just some basic operation that I can change to whatever I need). What I currently have is:

class ReadTextFile:

    def __init__(self, filename):
        file = open(filename, "r")
        ret = 0
        for line in file:
            for i in line:
                if i in "AEIOUaeiou":
                    ret += 1
        print("There are {} vowels in {}".format(ret, filename))
        file.close()


if __name__ == '__main__':
    while True:
        typeOfFile = input("What type of file are we reading from? (T)ext, or (C)? Type 'Q' to Quit")
        if typeOfFile not in "TCQ" or len(typeOfFile) != 1:
            print("I'm sorry, we cannot read that kind of file")
            continue
        if typeOfFile == 'T':
            fileToRead = input("What text file will we use?")
            ReadTextFile(fileToRead)
        if typeOfFile == 'C':
            print("Not yet implemented")
            continue
        if typeOfFile == 'Q':
            break

I am using PyCharm as an IDE since I really liked Eclipse but didn't want to mess with my Java set up for future classes and wanted to give other IDEs a try.

The issue I am running into is the fact that if I save a file as to "~/Testing.txt" then the code doesn't run and gives the error

Traceback (most recent call last):
  File "./ReadFile.py", line 30, in <module>
    ReadTextFile(fileToRead)
  File "./ReadFile.py", line 12, in __init__
    file = open(filename, "r")
FileNotFoundError: [Errno 2] No such file or directory: '~/Testing.txt'

however, if I instead type in "/home/myaccount/Testing.txt", which is the path to the file It runs as expected with no errors.

Note: if I type "cd ~/folderNameHere" and cd /home/myaccount/folderNameHere I get taken to the same place.

Is this a system issue or something that I can check for in my code in the event I wanted to send it to one of my classmates (will have a different home folder) since we talked about making this automation together.

Thank you for any help!

1 Answers1

0

You can use os.path.expanduser to replace the initial ~ character with the user's home directory:

import os

...

file = open(os.path.expanduser(filename), "r")
blhsing
  • 91,368
  • 6
  • 71
  • 106