Python win10 open函数一直显示路径不存在

VS0804 2018-07-12 10:27:52
各位大神,

帮忙看看这个报错是什么问题,windows,试过各种路径写法都不行

def test_create(name,msg):

desktop_path = 'C://user/Ryan/Desktop/'

full_path = desktop_path+name+'.txt'

file = open(full_path,'w')

file.write(msg)

file.close()

print('Done')



test_create('hello','hello,ryan')

---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-7-bac9aeb8aa6d> in <module>()
7 print('Done')
8
----> 9 test_create('hello','hello,ryan')

<ipython-input-7-bac9aeb8aa6d> in test_create(name, msg)
2 desktop_path = 'C://user/Ryan/Desktop/'
3 full_path = desktop_path+name+'.txt'
----> 4 file = open(full_path,'w')
5 file.write(msg)
6 file.close()

FileNotFoundError: [Errno 2] No such file or directory: 'C://user/Ryan/Desktop/hello.txt'

...全文
382 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
欢乐的小猪 2018-07-13
  • 打赏
  • 举报
回复
windows下路径格式为 S:\方言识别\数据
linux下路径格式为 /home/pig/PycharmProjects/tfstudy
一个是斜杠一个是反斜杠
VS0804 2018-07-13
  • 打赏
  • 举报
回复
重新建了一个文档,同样的方式了,竟然可以了,谢谢各位
silence cc 2018-07-13
  • 打赏
  • 举报
回复
楼主有2处错误:

1. Windows10的路径书写为'C:\\Users\\hp\\Desktop\\'
2. 路径拼接要用os.path.join(path1,path2,...)方法,而不是简单的字符串拼接


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os


def create_File(name,content):
desktop_Path = 'C:\\Users\\hp\\Desktop\\'
full_Path = os.path.join(desktop_Path,name + '.txt')
print(full_Path)
f = open(full_Path,'w')
f.write(content)
f.close()

create_File('hello','hello world')


测试结果:


VS0804 2018-07-12
  • 打赏
  • 举报
回复
改过了,还是不行
权限问题的话,应该会有permission denied的,我这个没有报这个错误,如果改成C盘,就有权限问题了
lovesf 2018-07-12
  • 打赏
  • 举报
回复
建议还是把/改成//看看,是不是win10配置不一样,还有,是不是权限问题,创建不了文件
VS0804 2018-07-12
  • 打赏
  • 举报
回复
文件是不存在啊,但是open(file,'w')不是如果文件不存在就创建一个吗?
改过了,还是不行呢
一样的代码,在win7上是可行的,在win10就不可以了
lovesf 2018-07-12
  • 打赏
  • 举报
回复
文件不存在,把每个目录标识/ 改为//
门口塘 2018-07-12
  • 打赏
  • 举报
回复

都可以正常运行啊,没有一句报错,你可以分开一句句试试看
门口塘 2018-07-12
  • 打赏
  • 举报
回复
引用 9 楼 VS0804 的回复:
不知道是不是win10的问题,我同事用win7的就可以,我的win10就一直显示不存在,路径写法都试过了,r'C:\啊,\\啊,/啊,所有表示windows绝对路径的方法都不行,报错都是一样的

我家里也是win10的,回家试试
VS0804 2018-07-12
  • 打赏
  • 举报
回复
不知道是不是win10的问题,我同事用win7的就可以,我的win10就一直显示不存在,路径写法都试过了,r'C:\啊,\\啊,/啊,所有表示windows绝对路径的方法都不行,报错都是一样的
lovesf 2018-07-12
  • 打赏
  • 举报
回复
\\不是//
wuxxzz2 2018-07-12
  • 打赏
  • 举报
回复
貌似是C://user/Ryan/Desktop/里不支持建立txt文件啊
wuxxzz2 2018-07-12
  • 打赏
  • 举报
回复
把'C://user/Ryan/Desktop/'改成'C:/user/Ryan/Desktop/'试试
门口塘 2018-07-12
  • 打赏
  • 举报
回复
引用 4 楼 VS0804 的回复:
改过了,还是不行
权限问题的话,应该会有permission denied的,我这个没有报这个错误,如果改成C盘,就有权限问题了

斜杠搞错了,应该是C:\\user\\Ryan\\Desktop\\

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧