Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading