如何在 python 中编写一个文件,并以变量作为路径?
我正在尝试打开一个文件,该文件在程序中保存之前。然后,我想将一些文本写入文件中。但这给了我以下错误,我已经在Google和Stackoverflow上寻找了解决方案,但是解决方案没有用。
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)
希望您能帮助我。感谢您提前的帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
playlist_file
变量包含字符串“&lt; _io.textiowrapper name ='c:/users/kevin/music/music/playlist.txt.txt'mode ='w'sopoding ='w'encoding ='cp1252'&gt; gt; “
;不仅“ c:/users/kevin/music/playlist.txt”
,导致问题。只需添加:
以便您的代码成为
可运行的示例:
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:
so that your code becomes
Runnable example: