欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 中文件的使用技巧

程序员文章站 2022-04-09 16:54:39
...

Python 中文件的使用技巧

注意:目录也是特殊的文件
基本函数:open,close,read,write不用多讲
有时候需要注意encoding参数,默认utf8中英文都可以,GBK用于汉语
记事本文件如果编码出错,用encoding ='ansi’即可
str类型经过encode编程bytes,decode之后转换为str

一个简单例子

text = '汉字'
txt = text.encode('GBK') #txt为 b'\xba\xba\xd7\xd6'
txt2 = text.encode('utf8')#txt2为 b'\xe6\xb1\x89\xe5\xad\x97'
txt_after = txt.decode('GBK')
txt_after2 = txt2.decode('utf8') #还原

回到正题,经常使用的一段代码

with open('data.txt','r') as data:
	dat = data.readlines()

通常配合字符串函数使用,进行一定的处理,这里什么都不做

dat = [line.strip() for line in dat]
dat = ','.join(dat).split(',') #得到一个列表
dat = str(dat) #必须转化成字符串,可以用map映射

假定已经处理完毕,写回文件

with open('data_after.txt','w') as fp:
	fp.write(dat)

先说glob库

glob('*') #当前路径所有文件,包括目录,类型为列表
glob('*.*')#带有扩展名的文件
glob('*.txt')#txt文件
glob('*.??')#扩展名为2字符文件

os,shutil库
判断是否存在subdir(目录),若不存在则建立:

import os,shutil
if not os.path.exists('subdir'):
    os.mkdir('subdir')
os.listdir('subdir') #返回subdir目录下的所有文件
shutil.copy('data.txt','subdir/file.txt')#复制文件
shutil.copytree('subdir','test')#复制目录
shutil.rmtree('test')#删除目录
for w in os.walk('D:/python/code'):
    print(w) #遍历目录

path的用法

from os import path
path.getsize('data.txt')#返回文件大小
path.abspath('subdir/file.txt')#返回绝对路径
folder,filename = path.split(path.abspath('subdir/file.txt'))#返回目录和文件名

进阶操作
查找文件

#基于os.walk()遍历目录

import os,re
import os.path as path

def find_path(pattern,base = '.'):
    '''
    根据模式查找base下的文件
    从base和开始遍历文件系统
    返回匹配模式的文件名列表
    '''
    regex = re.compile(pattern)
    matches = []
    for root,dirs,files in os.walk(base):
        for f in files:
            if regex.match(f):
                matches.append(path.join(root,f))
    return matches
	
def find_dirs(pattern,base = '.'):
    '''
    同上,对目录操作
    '''
    regex = re.compile(pattern)
    matches = []
    for root,dirs,files in os.walk(base):
        for d in dirs :
            if regex.match(d):
                matches.append(path.join(root,d))
    return matches
	
def find_all(pattern,base = '.'):
	matches = find_dirs(pattern,base)
	matches += find_path(pattern,base)
	return matches
	
def apply_to_files(pattern,function,base = '.'):
	regex = re.compile(pattern)
	errors = []
	for root,dirs,files in os.walk(base):
		for f in files:
			if regex.match(f):
				try:
					function(path.join(root,f))
				except:
					errors.append(path.join(root,f))
	return errors

最后是命令行的一些操作

import subprocess as sub
import os
import shutil
sub.call(['cmd','/c','dir','/b'])
sub.call(['cmd','/c','dir','/b'],stdout = open('ls.txt','w'))
sub.call(['cmd','/c','type','ls.txt'])
#打印屏幕尺寸
print(os.environ['HOME'])
cols,lines = shutil.get_terminal_size()
print(cols,lines)
#列出目录和文件信息
print(os.listdir('..'))
cwd = os.getcwd()
print(cwd)
print(os.listdir(cwd))
print(os.stat('ls.txt'))
print("\n")
ls = sub.Popen('cmd /c dir /b',stdout = sub.PIPE)

#另一种输出方式
#lsout = ls.communicate()[0]
#print(lsout)

for o in ls.stdout:
    print(o)

相关标签: 日记 python