• python之文件操作


          使用python进行文件操作

          使用:

              场景一:     逐行读取文件中的内容

    filename = 'sentiment_score.txt'
    
    f = open(filename,'r', encoding='UTF-8')
    line = f.readline()
    while line:
        print(line, end='')
        line = f.readline()
    
    f.close()

      场景二: 处理文件与路径标准库libpath

    #!/usr/bin/env python
    from pathlib import Path
    
    log_dir = Path("logs/")
    log_file = log_dir / "path.log"
    fb = open(log_file)
    print(log_file.read())

    请注意两点:

    • 在pathlib中请直接用正斜杠(“/”)。Path对象可以将正斜杠转换成当前操作系统应该使用的正确斜杠。Nice!
    • 如果想在某个Path对象后添加内容,只要在代码里使用“/”操作符(也就是除号!?)。跟一遍又一遍地敲os.path.join(a, b)的日子说拜拜吧!

    我们可以不用调用open()或者close()之类的函数,而直接读文件的内容   

    log_dir = Path("logs/")
    log_file = log_dir / "path.log"
    
    print(log_file.read_text())

      常见问题:

        1. UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 

                  解决:  指定utf8字符集进行读取,  打开文件的时候,设置字符集 encoding='utf-8'

  • 相关阅读:
    CentOs7-替换下载源
    CentOs7-常用命令
    Django Nginx+uwsgi 安装配置
    Linux操作系统下文件作用
    U盘创建macOS安装盘
    国内开源镜像站点汇总
    gcd常见用法
    mac rvm 升级 ruby 安装cocoapod 指定版本
    confluence 搭建 wiki 并破解
    homebrew 安装 java 指定版本
  • 原文地址:https://www.cnblogs.com/xingxia/p/python_file.html
Copyright © 2020-2023  润新知