繁体   English   中英

当我使用os.walk来获取python 3上的文件路径时,此错误是什么意思?

[英]What does this error mean when I use `os.walk` to get the files path on python 3?

错误太长,因此我没有将其放在标题中。 这是错误:

Traceback (most recent call last):
  File "./auto_change_shebang_and_permission.py", line 12, in <module>
    shebang = f.readline()
  File "/usr/lib/python3.4/codecs.py", line 319, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8c in position 3: invalid start byte

但是我以前从未见过此错误。 我写了一个程序来自动更改Linux上的SheBang ,它使用os.walk获取文件路径并打开它们,这是程序:

for root, dirs, files in os.walk(sys.argv[1]):                               
    for name in files:
        # to except the hidden file                                            
        if root[:3] == './.':                                                
            pass                                                             
        elif name[0] == '.':                                                 
            pass    
        # open the file, read the SheBang, and change it.
        else:                                                              
           with open(os.path.join(root, name), 'r') as f:                    
               shebang = f.readline()                                        
               if shebang[:2] != '#!':                                       
                   with open(os.path.join(root, name), 'w') as e:            
                       e.write('#!/usr/bin/env python3\n'+shebang+f.read())  
               else:                                                         
                   if shebang != '#!/usr/bin/env python3':                   
                       with open(os.path.join(root, name), 'w') as e:        
                           e.write('#!/usr/bin/env python3\n'+f.read())      

               os.chmod(os.path.join(root, name), 493)

它正在工作,但是会引发该错误。 我不知道哪里错了。

好吧,现在我明白了怎么了。 因为if root[:3] == './.' 仅在sys.argv[1]工作.

然后,就像@AnandSKumar所说的。 程序得到的文件不是文本文件。


所以现在我像这样编辑代码:

if fnmatch(root, sys.argv[1]+'/.*'):
    pass

现在,它的运行非常好,谢谢@AnandSKumar。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM