Python 基础汇总2 之文件读写

# !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'))
    

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值