• 【python】python文件操作


    python文件操作

    1.文本文件的打开模式

    import os
    文件句柄 = open('文件路径+文件名', '模式')
    
    • 1
    • 2
    例子
    f = open("test.txt","r",encoding = “utf-8)
    f = open(file = "d:/python/test.txt","r",encoding = “utf-8)
    
    • 1
    • 2
    • 3
    “r” ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
    “w”, 只写模式【不可读;不存在则创建;存在则清空内容】
    "a",只追加写模式【不可读;不存在则创建;存在则只追加内容】
    
    "+" 表示可以同时读写某个文件
    "r+",读写【可读,可写】
    "w+",写读【可读,可写】
    "a+",写读【可读,可写】
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2.read()、readline() 、readlines()

    with open(path, 'r', encoding='utf-8') as f_read:  #python读文件
          lines = f_read.readlines()  #读取每一行数据,存放于列表中
          lines = f_read.read() #读取整个文件
          lines = f_read.readline() #读取一行内容,光标移动到第二行首部以字符串的形式返回结果
    
    • 1
    • 2
    • 3
    • 4

    3.write()、writelines( )

    write()要写入字符串
    writelines()既可以传入字符串又可以传入一个字符序列,并将该字符序列写入文件。 注意必须传入的是字符序列,不能是数字序列。

    f.write('1111\n222\n') #针对文本模式的写,需要自己写换行符
    f.write('1111\n222\n'.encode('utf-8')) #针对b模式的写,需要自己写换行符
    f.writelines(['333\n','444\n']) #文件模式
    f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')]) #b模式
    
    • 1
    • 2
    • 3
    • 4

    4. f.close() f.closed()

    f.close() #关闭文件  
    f.closed()#查看文件是否关闭
    
    • 1
    • 2

    5.with open as f打开方法

    这种打开文件的方式不用写f.closed关闭文件

    with open('/path/to/file', 'r') as f:
    with  open("test.txt","r",encoding = “utf-8) as f:
    
    
    
    • 1
    • 2
    • 3
    • 4

    6.f.encoding

    取文件打开的编码

    f = open("test11.py","w",encoding="gbk")
    f.write("222\n")
    f.close()
    print(f.encoding)
    
    • 1
    • 2
    • 3
    • 4
    输出
    gbk
    
    • 1
    • 2

    【推荐阅读】

    【推荐阅读】

    示例:

     def read_origin_data(self, origin_data_path=ORIGIN_DATA_PATH, flag=None):
            all_data_paths = os.listdir(origin_data_path)  #os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
    
            for each_path in all_data_paths:
                path = origin_data_path + '/' + each_path+'/' + each_path
    
                all_user_loads = {}
    
                with open(path, 'r', encoding='utf-8') as f_read:  #python读文件
                    lines = f_read.readlines()  #读取每一行数据,以列表得形式存储
                    for n,line in enumerate(tqdm.tqdm(lines)): #Tqdm 是一个快速,可扩展的Python进度条
                        if n == 50000:
                            pass
                        current_user = int(line.split(' ')[0])  # split() 通过指定分隔符对字符串进行切片  输出分割的第一个
                        current_time = int(line.split(' ')[1])   #输出分割的第二个
                        current_load = float(line.split(' ')[2].strip())*1000 
                        # strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
                        # 该方法只能删除开头或是结尾的字符,不能删除中间部分的字符
                        time_load = [current_time, current_load]
    
                        if current_user not in all_user_loads.keys():
                            all_user_loads[current_user] = [time_load]
                        else:
                            all_user_loads[current_user].append(time_load)
                    # break
    
                f_read.close()  #关闭文件
                # 给用户数据排序
                all_user_nums = all_user_loads.keys()
                for user in all_user_nums:
                    current_user_data = all_user_loads[user]
                    current_user_data = np.array(current_user_data)  #array创建数组
                    sort_index = np.lexsort((current_user_data[:, 1], current_user_data[:, 0]))
    
                    sorted_user_data = current_user_data[sort_index, :]
                    all_user_loads[user] = sorted_user_data
    
                if flag == 'day':
                    print("正在对数据预处理!")
                    days_user_loads = self.all_to_days(all_user_loads)
                    print("数据预处理完成!")
                elif flag == 'month':
                    print("正在对数据预处理!")
                    days_user_loads = self.all_to_months(all_user_loads)
                    print("数据预处理完成!")
                else:
                    days_user_loads = self.all_to_years(all_user_loads)
    
                print("正在写入数据!")
                self.write_data(days_user_loads, WRITE_DATA_PATH, flag)
                print("写入数据完成!")
    
            return
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
  • 相关阅读:
    配置 Kafka 生产者属性
    Spring Cloud Alibaba+saas企业架构技术选型+架构全景业务图 + 架构典型部署方案
    http和https区别,第三方证书如何保证服务器可信
    Linux驱动【day2】
    spark中生成时间序列数据的函数stack和sequence
    一起瓜分20万奖金!第三届火焰杯软件测试大赛开始公开选拔!
    【Leetcode】667. 优美的排列 II
    Tableau:详细表达式(LOD表达式)的计算过程
    兄弟兄弟,在git中的使用.gitignore忽略不想要提交的文件,了解一下呗
    Java.lang.Class类 getCanonicalName方法有什么功能呢?
  • 原文地址:https://blog.csdn.net/qq_42292095/article/details/125508473