python 基础系列10-文件操作

# python 基础系列10-文件操作

# 引入sys库
import sys
import copy
from functools import reduce

if __name__ == '__main__':
    # 读取txt文本 读取需要指定权限
    myfile = open('C:\\Users\\Administrator\\Desktop\\test.txt', 'r')
    # 进行操作
    # mystr =myfile.read()
    # 读取单行
    # mystr2 =myfile.readline()
    # print(mystr2)

    # 全读取出来保存在列表
    mystr3 = myfile.readlines()  # ['11122\n', 'dfdsdsf\n', 'dsffs\n', '222\n', '333\n', '355fff']
    print(mystr3, len(mystr3))

    # 修改访问位置
    myfile.seek(0, 0)

    mylist = []
    # 遍历循环
    for var in myfile:
        mylist.append(var)
        print(var)
    print(mylist)

    # 写文件
    myfile2 = open('C:\\Users\\Administrator\\Desktop\\test.txt', 'w')
    # myfile2.write('ddddd') #这里会覆盖

    # 设置权限 ,结果会是追加
    myfile3 = open('C:\\Users\\Administrator\\Desktop\\test2.txt', 'a')
    myfile3.write('dfrggg')

    # 当前写入是写入到了内存里面,我们需要写入到磁盘,两种方式:文件关闭
    myfile3.flush()
    myfile3.close()

    #文件拷贝
    myfile_c1 = open('C:\\Users\\Administrator\\Desktop\\test3.txt', 'r')
    myfile_c2 = open('C:\\Users\\Administrator\\Desktop\\test4.txt', 'a')

    mystr_c1 = myfile_c1.readlines()
    print(mystr_c1)
    myfile_c2.writelines(mystr_c1)
    myfile_c1.close()
    myfile_c2.close()
    
    # 权限 r w a  r+ w+ a+权限

猜你喜欢

转载自blog.csdn.net/qq_31866793/article/details/104367890