python程序设计之文件_Python程序设计之文件操作(2)

print(sub_path)

if os.path.isdir(sub_path):

visitdir(sub_path)

path1='C:UsersQinHsiuPythonProjectsStringoo'

visitdir(path1)

方法二:使用walk()函数来实现

#方法二,通过walk()方法指定遍历目录

def visidir2(path):

if not os.path.isdir(path):

print('error!',end='n')

return

list_dir=os.walk(path)

for root,dirs,files in list_dir: #遍历该元组目录和文件信息

for di in dirs:

print(os.path.join(root,di),end='n') #获取完整路径

for f in files:

print(os.path.join(root,f),end='n') #获取绝对路径

visidir2(path1)

⑤计算字符的crc32的值

import zlib #计算任意字符串的CRC32值

print('1234'.encode(),end='n')

print(zlib.crc32('1234'.encode()),end='n')

import binascii #计算任意字符串的CRC32值

print(binascii.crc32('1234'.encode()),end='n')

⑥计算文本行最长字符串长度

方法一

#计算文本行最长行的字符串的长度

fp=open('1.txt','r+')

allLines=[len(line.strip()) for line in fp]fp.close()

logest=max(allLines)

print(logest,end='n')

方法二

fp1=open('1.txt','r+')

logest1=max(len(line.strip()) for line in fp1)

fp1.close()

print(logest1,end='n')

⑦计算md5值

import string

import _md5 #计算md5值,用于文件的完整性保护

import hashlib

import sys

import os

md5value=hashlib.md5()

md5value.update('1234'.encode())

md5value=md5value.hexdigest()

print(md5value,end='n')

md5value=_md5.md5()

md5value.update('12345'.encode())

md5value=md5value.hexdigest()

print(md5value,end='n')

⑧md5计算器

filename=sys.argv[1]if os.path.isfile(filename):

with open(filename,'r') as f:

lines=f.readlines()

data=''.join(lines).encode()

print(hashlib.md5(data).hexdigest(),end='n')

#计算哈希模糊值,用来得出两个文件相似百分比

#from ssdeep import ssdeep

#s=ssdeep.hash_from_file(filename)

#print(s,end='n')

⑨通过文件头来查看文件类型

def look(filename):

f=open(filename,'r')

first=tuple(f.read(4))

#print(first,end='n')

f.close()

m=('T','X','T','8')

print(m,first,end='n')

return first==m

print(look('1.txt'),end='n')

⑩判断两个文件是否相等

import difflib #判断两个文件是否相同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值