在Python中使用os.path.exists()函数时返回假如何解决

  介绍

在Python中使用os.path.exists()函数时返回假如何解决?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

如下面所示,如果我们用文件的readline或readline,在每一行后面都有一个\ n回车符

直接os.path.exists (readline)时总会返回假

在祝辞祝辞,得到os.path  import 存在   在祝辞祝辞,存在(& # 39;dog.png& # 39;)   真正的   在祝辞祝辞,存在(& # 39;dog.png \ n # 39;)   假

使用item.strip (& # 39; \ n # 39;) #前面的项目为我定义的变量

去掉后再传递给os.path.exists(项目)就好了。

<强>补充:当os.path.exists(路径)的路径中包含有空格时返回结果为错误的解决方案

之前有个问题一直没有解决,当路径中或文件名中存在空格时,用os.path.exists(路径)判断是否存在时,都会返回错误的。百思不得其解。今天在用ipython偶到想到想了解一下到底是什么原因?

事实上,当用输入()接收路径输入时,路径中有空格时,生成的str是不一样的。如下:

拷贝[4]:,path =,输入(& # 39;请将文件拖入:& # 39;)

请将文件拖入:“C: \ xxxxx \ \用户桌面\文件名space.txt"

拷贝[5]:路径   出[5]:& # 39;“C: \ \ \ \ xxxxx \ \用户桌面\ \ filename  with  space.txt" & # 39;   ,   [6]:拷贝,path2 =,输入(& # 39;请将文件拖入:& # 39;)

请将文件拖入:C: \ \ xxxxx桌面\ \ filenamewithspace用户。txt

拷贝[7]:path2   出[7]:& # 39;C: \ \ \ \ xxxxx \ \用户桌面\ \ filenamewithspace.txt& # 39;   ,   [8]:拷贝,os.path.exists(路径)   [8]:假   ,   [9]:拷贝,os.path.exists (path2)   出[9]:真正的

很明显,带有空间时生了的str多了一层““字符串,故将多余的““去掉应该就可以了。以下为验证实例

拷贝[10]:,path3 =, path.replace (& # 39; \“& # 39;,, & # 39; & # 39;)   ,   [11]:拷贝path3   出[11]:& # 39;C: \ \ \ \ xxxxx \ \用户桌面\ \ filename  with  space.txt& # 39;   ,   [12]:拷贝,os.path.exists (path3)   出[12]:真正的

当前读取手机存储空间的文件时,当手机根目录中存在还中文或带空格的文件/文件夹时(如下图),就会出的错。

在Python中使用os.path.exists()函数时返回假如何解决

一般这时为了要读出这些文件夹,一般的操作为:

拷贝[23]:,cmd =, & # 39; adb  shell  ls /sdcard/& # 39;   ,   [24]:拷贝,file_list =, os.popen (cmd) . readlines ()   ---------------------------------------------------------------------------   UnicodeDecodeError ,,,,,,,,,,, Traceback  (most  recent  call 最后)   & lt; ipython-input-24-b7ae01065f81>,拷贝;& lt; module>   - - - - -祝辞,1,file_list =, os.popen (cmd) . readlines ()   ,   UnicodeDecodeError: & # 39; gbk # 39;, codec 停下来# 39;t  decode  byte  0 xae  position  10:拷贝,illegal  multibyte 序列

一般会报以上的错误或是不报的错,但是中文文件/文件名可能为乱码,从以下的帮助(os.popen)可以了解后,os.popen()也是不能设置编码方式的,无解哈。

拷贝[25]:,帮助(os.open)
  Help 提醒built-in  function  open 拷贝module  nt:
  ,
  open(路径,旗帜,,模式=511,,,,dir_fd=没有)
  Open 才能a  file  for  low  level  IO只Returns  a  file  descriptor (整数)。
  ,
  If 才能dir_fd  is  not 没有,,it  should  be  a  file  descriptor  open 用a 目录,
  ,,以及path  should  be 相对;,path  will  then  be  relative 用that 目录。
  dir_fd 才能may  not  be  implemented 提醒your 平台。
  ,,If  it  is 不可用,,using  it  will  raise  a  NotImplementedError。

所以又回到之前写的一篇文章上,要用subprocess.run()全面替换掉os.system/os.popen,这样就可以解决这些问题了。

拷贝[27]:,cmd =, & # 39; adb  shell  ls /sdcard/& # 39;   ,   [28]:拷贝,file_list =, subprocess.run (cmd, capture_output=True,,编码=& # 39;utf - 8 # 39;,, shell=True) .stdout。   ,,…:splitlines ()   ,   [29]:拷贝,file_list (0:3)   出[29]:[& # 39;0000 & # 39;,& # 39;00新文件夹& # 39;,,& # 39;00新文件夹,测试# 39;]

在Python中使用os.path.exists()函数时返回假如何解决