# !usr/bin/env python
# -*- coding:utf-8 -*-
import os
import os.path
import random
import struct
#python常见基础知识汇总
'''
内置对象:
数字、字符串、列表、字典、元组、文件、集合
其他类型:类型、None、布尔
编程单元:函数、模块、类
与实现相关的类型:编译的代码堆、栈跟踪
'''
#文件
#遍历文件
rootdir = 'D:\\pan'
if os.path.exists(rootdir):
#root:遍历到的目录,dirs:root目录下的文件夹 files:root目录下的文件
for (root, dirs,files) in os.walk(rootdir):
for dirname in dirs:
print('Root is:',root)
print('Folders is:',dirname)
for filename in files:
print('Files in Root ',os.path.join(root,filename))
#判定是否为文件
if os.path.isfile(rootdir):
print(rootdir,' is file')
else:
print(rootdir,' is not file')
#是否存在
if os.path.exists('data.txt'):
print(os.path.getsize('data.txt'))
#获取文件大小
print(os.path.getsize('data.txt'))
'''
文件读写格式:
r:读 w:写 a:追加
r+:可读可写,文件不存在时报错IOError
w+:可读可写,文件若不存在就创建
a+:可追加可写,文件若不存在就创建
对一个的二进制读写:
rb、wb、ab、rb+、wb+、ab+
'''
#读、写
fw = open('data.txt','w')
fw.write('你好\nPython\n')
fw.close()
fr = open('data.txt','r')
txt = fr.read()
fr.close()
print(txt)
fr = open('data.txt','r')
txts = fr.readlines()
fr.close()
for txt in txts:
print(txt)
fr = open('data.txt','r')
fr.seek(2) #指定光标在文件中的位置
print(fr.read(2)) #读取2个字符
fr.close()
#读、写 不用考虑文件关闭
with open('data.txt','r') as file:
for line in file:
print(line)
with open('data.txt','a+') as fw:#追加
fw.write('Welcome Python\n')
with open('data.txt','r') as fr:
print(fr.read())
with open('data.txt','a+') as fw:
fw.seek(0)
fw.truncate() #删除光标后的内容
#二进制读写
fr = open('img.jpg','rb')
print(fr.read())
fr.close()
with open('data2.txt','wb') as fw:
fw.write('Welcome Python\n'.encode('ascii'))