如何使用变量作为路径在 python 中编写文件?

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

我想在程序中打开一个我之前保存的文件。然后我想在文件中写入一些文本。但它给了我以下错误,我已经在 google 和 Whosebug 上寻找解决方案,但解决方案没有用。

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

和我的代码:

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)

希望你能帮助我。我提前感谢你的帮助。

playlist_file变量包含字符串"<_io.TextIOWrapper name='C:/Users/kevin/Music/playlist.txt' mode='w' encoding='cp1252'>";不仅仅是 "C:/Users/kevin/Music/playlist.txt",导致了这个问题。

只需添加:

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

这样你的代码就变成了

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)

可运行示例:

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)