Search code examples
pythonfiletkintersavefiledialogfiledialog

How do I write a File in python, with a variable as a path?


I am trying to open a file, which I save before, in the program. Then I want to write some text, into the file. But it gives me the following Error, I have already looked for solutions in google and also here on stackoverflow, but the solutions didn't work.

OSError: [Errno 22] Invalid argument: "<_io.TextIOWrapper name='C:/Users/kevin/Music/playlist.txt' mode='w' encoding='cp1252'>"

and my Code:

def create_playlist():
playlist_songs = filedialog.askopenfilenames(initialdir=r'C:\Users\kevin\Music')
str(playlist_songs)
playlist_file = str(filedialog.asksaveasfile(mode="w",defaultextension=".txt"))
with open (playlist_file, 'w') as f:
    f.write(playlist_songs)

I hope you can help me. I thank you for your help in advance.


Solution

  • The playlist_file variable contains the string "<_io.TextIOWrapper name='C:/Users/kevin/Music/playlist.txt' mode='w' encoding='cp1252'>"; not just "C:/Users/kevin/Music/playlist.txt", causing the issue.

    Simply add:

    playlist_file = playlist_file[25: playlist_file.index("' ")]
    

    so that your code becomes

    def create_playlist():
        playlist_songs = filedialog.askopenfilenames(initialdir=r'C:\Users\kevin\Music')
        playlist_file = str(filedialog.asksaveasfile(mode="w",defaultextension=".txt"))
        playlist_file = playlist_file[25: playlist_file.index("' ")]
        with open (playlist_file, 'w') as f:
            f.write(playlist_songs)
    

    Runnable example:

    from tkinter import filedialog
    
    playlist_songs = filedialog.askopenfilenames(initialdir=r'C:\Users\kevin\Music')
    playlist_file = str(filedialog.asksaveasfile(mode="w",defaultextension=".txt"))
    playlist_file = playlist_file[25: playlist_file.index("' ")]
    with open (playlist_file, 'w') as f:
        f.write(playlist_songs)