Python 10 文件及IO操作

文件基本操作(读写、打开关闭)

def my_write():
    file = open('a.txt', 'w', encoding='utf-8')
    file.write('伟大的中国梦')
    file.close()

def my_read():
    file = open('a.txt', 'r', encoding='utf-8')
    s = file.read()
    print(type(s), s)
    file.close()

if __name__ == '__main__':
    my_write()
    my_read()

文件写入操作

def my_write(s):
    file = open('b.txt', 'a', encoding='utf-8')
    # a表示追加,如果有继续追加内容,如果没有就创建

    file.write(s)
    file.write('\n')
    file.close()


def my_write_list(file, lst):
    f = open(file, 'a', encoding='utf-8')
    f.writelines(lst)
    f.close()

if __name__ == '__main__':
    my_write('伟大的中国梦')
    my_write('北京欢迎你')

    lst = ['name\t', 'age\t', 'score\n', 'lili\t', '30\t', '98']
    my_write_list('c.txt', lst)

运行了好几遍的结果:

 

文件读取

def my_read(filename):
    file = open(filename, 'w+', encoding='utf-8')
    file.write('你好啊')  # 写入完成,此时文件的指针在最后
    # seek 修改文件指针的位置
    file.seek(0)
    # 读取
    # s = file.read() # 读取全部
    # s = file.read(2) # 读取两个字符
    # s = file.readlines()  # 读取所有,一行为列表中的一个元素
    file.seek(3)
    s = file.read()
    print(type(s), s)

    file.close()

if __name__ == '__main__':
    my_read('d.txt')

文件复制

def copy(src, new_path):
    file1 = open(src, 'rb')
    file2 = open(new_path, 'wb')

    s = file1.read()
    file2.write(s)

    file2.close()
    file1.close()

if __name__ == '__main__':
    src = './google.jpg'
    new_path = '../Python/copy.jpg'
    # ..退出当前文件夹,到上一个目录下
    copy(src, new_path)
    print('文件复制完毕')

文件管理

def write_fun():
    with open('aa.txt', 'w', encoding='utf-8') as file:
        file.write('2022北京东奥欢迎您')


def read_fun():
    with open('aa.txt', 'r', encoding='utf-8') as file:
        print(file.read())


def copy(src_file, target_file):
    with open(src_file, 'r', encoding='utf-8') as file:
        with open(target_file, 'w', encoding='utf-8') as file2:
            file2.write(file.read())

if __name__ == '__main__':
    write_fun()
    read_fun()
    copy('./aa.txt','./dd.txt')
    

数据组织维度及存储

def my_write():
    lst = ['张三', '李四', '王五']
    with open('student.csv', 'w') as file:
        file.write(','.join(lst))  # 将列表转成字符串


def my_read():
    with open('student.csv', 'r') as file:
        s = file.read()
        lst = s.split(',')
        print(lst)


#  存储和读取二维数据
def my_write_table():
    lst = [
        ['商品名称', '单价', '采购数量'],
        ['水杯', '98.5', '20'],
        ['鼠标', '89', '100']
    ]
    with open('table.csv', 'w', encoding='utf-8') as file:
        for item in lst:
            line = ','.join(item)
            file.write(line)
            file.write('\n')

def my_read_table():
    data = []
    with open('table.csv', 'r', encoding='utf-8') as file:
        lst = file.readlines()  # 每一行是列表中一个元素
        for item in lst:
            new_lst = item[:len(item)-1].split(',')
            data.append(new_lst)
    print(data)


if __name__ == '__main__':
    my_write()
    my_read()
    my_write_table()
    my_read_table()

JSON 高维数据的存储和读取

import json
lst = [
    {'name': 'lili', 'age': 18, 'score': 90},
    {'name': 'tom', 'age': 19, 'score': 97},
    {'name': 'bilili', 'age': 16, 'score': 94},
]

s = json.dumps(lst, ensure_ascii=False, indent=4)
print(type(s))
print(s)

# 解码
lst2 = json.loads(s)
print(type(lst2))
print(lst2)

# 编码到文件中
with open('student.txt','w') as file:
    json.dump(lst, file, ensure_ascii=False, indent=4)

# 解码到程序中
with open('student.txt', 'r') as file:
    lst3 = json.load(file)
    print(type(lst3))
    print(lst3)
    

OS模块

import os
print('当前工作路径:', os.getcwd())
lst = os.listdir()
print('当前路径下所有目录及文件:', lst)
print('指定路径下所有目录及文件:', os.listdir('D:/Python'))

# os.makedirs('./aa/bb/cc')
# os.rmdir('./admin')  单层
# os.removedirs('./aa/bb/cc')  删除多层

# 改变路径
os.chdir('D:/Python')
print(os.getcwd()) # python文件路径没有变,但是程序运行的路径改变了
print('-'*60)

# 遍历目录树
for dirs, dirlst, filelst in os.walk('D:/Python'):
    print(dirs)
    print(dirlst)
    print(filelst)
    print("-"*40)

import os
# os.remove('./student.csv')
# os.rename('student.txt', 'scores.txt') 重命名

import time
def date_format(longtime):
    s = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(longtime))
    return s

info = os.stat('./scores.txt')
print(type(info))
print(info)

print('最近一次访问时间:', date_format(info.st_atime))
print('在windows操作系统中显示的文件创建时间:', date_format(info.st_ctime))
print('最后一次修改时间:', date_format(info.st_mtime))
print('文件的大小(字节):', info.st_size)

# 启动路径下的文件
# os.startfile('calc.exe')
# os.startfile(r'C:\Windows\System32\cmd.exe')

import  os.path
print('获取目录或文件的绝对路径:', os.path.abspath('./b.txt'))
print('判断目录或文件在磁盘上是否存在:', os.path.exists('b.txt'))
print('判断目录或文件在磁盘上是否存在:', os.path.exists('aaa.txt'))
print('判断目录或文件在磁盘上是否存在:', os.path.exists('./admin'))

print('拼接路径:', os.path.join('D:\Python\learn', 'b.txt'))
print('分割文件名和文件后缀名:', os.path.splitext('b.txt'))
print('提取文件名:', os.path.basename(r'D:\Python\learn\b.txt'))
print('提取路径:', os.path.dirname(r'D:\Python\learn\b.txt'))

print('判断一个路径是否为有效路径:', os.path.isdir(r'D:\Python\learn'))
print('判断一个路径是否为有效路径:', os.path.isdir(r'D:\Python\learnn'))
print('判断一个文件是否为有效文件:', os.path.isfile(r'D:\Python\learn\b.txt'))

  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值