首页 / 教程

python调用open()打开文件时为什么路径出错

时间:2023-06-15 14:10:30阅读:0

python调用open()打开文件时为什么路径出错

  python的open()打开文件 代码如下

  def main():
  infile =open("C:\Users\Spirit\Desktop\bc.txt",'r')
  data = infile.read()
  print(data)
  main()

  然而结果总报错invaild argument 或者cant found such file ***

  查找问题后 发现是由于python中的 ‘\' 是转义符号,要想输出\ 的办法有两种

  1 、在\后再加\ 就是\\ 的形式

  把第二行改为infile =open("C:\\Users\\Spirit\\Desktop\\bc.txt",'r') 即可

  2、在路径前加个 r ,意思是按原始字符处理 。

  eg

infile =open(r"C:\Users\Spirit\Desktop\bc.txt",'r')


本站文章均来自互联网,仅供学习参考,如有侵犯您的版权,请邮箱联系我们删除!

猜你喜欢