muad-dweeb
muad-dweeb

Reputation: 1175

I/O Error with open()

class NewTab():
    def __init__(self, song_title, artist_name):
        self.song_title  = song_title
        self.artist_name = artist_name
        name1    = self.artist_name + "_" + self.song_title
        name2    = name1.replace(" ", "")
        new_file = open("~/Documents/"+name2+".txt", "a+")

tab = NewTab(raw_input("Song Title: "), raw_input("Artist Name: "))

I am trying to create a new file (assuming it doesn't already exist) whose name is generated from two strings of User input. For example:

"Song Title: "  >> Personal Jesus
"Artist Name: " >> Depeche Mode

should result in creating: ~/Documents/DepecheMode_PersonalJesus.txt


Unfortunately I am always left with:

IOError: [Errno 2] No such file or director: '~/Documents/DepecheMode_PersonalJesus.txt'

I have tried different open() modes, such as "w", "w+" and "r+" to no avail. I have also tried placing name1, name2, and new_file into a method outside of __init__ like so:

    def create_new(self):
        name1    = self.artist_name + "_" + self.song_title
        name2    = name1.replace(" ", "")
        new_file = open("~/Documents/"+name2+".txt", "a+")

tab.create_new()

but this results in the exact same Error.

I have set my /Documents folder Permissions (Owner, Group, Others) to Create and delete files.

Beyond that, I am at a complete loss as to why I cannot create this file. It is clearly structuring the file name and directory the way that I want it, so why won't it go ahead and create the file?

Upvotes: 1

Views: 1290

Answers (2)

user3520669
user3520669

Reputation:

If you don't necessarily need to use "a+" then having "wb" as a second parameter will automatically open a file.

foo = open("bar", "wb")

Upvotes: 2

marscher
marscher

Reputation: 830

Use os.path.expanduser() function to get a full valid path with "~" resolved and pass this to open()

    new_file = open(os.path.expanduser("~/Documents/")+name2+".txt", "a+")

this will resolve "~" to something like /home/user and join it with the rest of the path elements.

Upvotes: 3

Related Questions