python使用中的问题记录

1、删除空目录
import os
os.removedirs(path)
#循环删除空目录
for root, dirs, files in os.walk(dir_path):
    if not os.listdir(root):
        os.rmdir(root)

roots:代表需要遍历的根文件夹
root:表示正在遍历的文件夹的名字(根/子)
dirs:记录正在遍历的文件夹下的子文件夹集合
files: 记录正在遍历的文件夹中的文件集合

2、删除指定文件夹(无论是否为空)

如果遇到OSError: [WinError 145]这种报错,请使用这个方法来删除文件夹

import shutil
shutil.rmtree(path) 
3、删除文件
import os
os.remove(path) 

循环删除指定文件
4、其他
os.path.dirname(filepath) 获取文件的上一级目录
os.path.realpath(file) 获取当前file的路径
5、 UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa6 in position 670: illegal multibyte seq

添加:encoding=“utf-8”

with open(filepath, 'r',encoding="utf-8") as fr:
6、判断文件是否存在
os.path.exists(filepath)
7、执行脚本的时候传入的参数

脚本执行:from对应的就是path,desc对应的就是desc

python.exe compile_file.py -path %from% -desc %desc% 

compile_file.py的main中执行:

import argparse

if __name__ == "__main__":
	parser = argparse.ArgumentParser(u"工具")
	parser.add_argument('-path', '--projectPath', help=u"项目的根路径", action='store', dest="rootPath", type=str,default="")
	
	parser.add_argument('-desc', '--descPath', help=u"目标路径", action='store', dest="descPath", type=str,default="")
	
	args = parser.parse_args()
	#获取输入的参数
	source_dir = args.rootPath
	dest_dir = args.descPath
8、直接运行py文件,提示输入
source_dir = input('Please Enter Project path:')
9、使用try catch
try:
    f = open()
    f.close()
except FileNotFoundError:
    print "FileNotFoundError."
except PermissionError:
    print "PermissionError."
10、python中写入txt文件的换行
f.write('\n') #文本\n不会换行
f.write('\r\n') #正确的写入换行
11、python中文件操作读写,文件如果不存在会创建新文件并进行内容写入

覆盖内容

 file = open(filepath, 'w') 或者 file = open(filepath, 'w+')

不覆盖已存在的内容,若目标文件中本身存在内容,不会被覆盖掉

 file = open(filepath, 'a')
12、UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xc1 in position 0: invalid start byte

遇到这种报错的是因为其他编码格式的文件内容在读的时候使用了utf-8读取。这个时候有两种修改方法。
方法一:修改报错文件为指定的编码格式
方法二:读取的时候不要设置encoding=“utf-8”,使用默认的。

使用默认的情况下可能会报错:
UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0x80 in position 20: illegal multibyte sequence
这个时候还是建议使用方法一,修改文件格式编码。

13、检查文件编码格式

注意目前这里我只能用rb,用r的话报错

#检查文件编码格式
f = open(filepath, 'rb')
data = f.read()
print(chardet.detect(data))

打印结果

{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
14、python 使用shutil.copy 进行目录copy时报错IOError: [Errno 13] Permission denied

解决方法:使用shutil.copy2

import shutil
shutil.copy2(filepath, newFilePath)
15、编码格式

py文件顶部增加

# -*- coding: utf-8 -*-
#coding=utf-8
16、解压zip
import os, zipfile
#解压单独文件password一般为None
def unzip_single(srcfile, destdir, password):
    if password:
        password = password.encode()
    zf = zipfile.ZipFile(srcfile)
    try:
        zf.extractall(path=destdir, pwd=password)
    except RuntimeError as e:
        print(e)
    zf.close()

#示例
if __name__ == '__main__':
    froms = 'E:\\from\\a.zip'
    tos = 'E:\\to'
    password = None
    unzip_single(froms, tos, password)

猜你喜欢

转载自blog.csdn.net/fanwei4751/article/details/105948204