原链接:https://blog.csdn.net/m0_37745438/article/details/79573414

python提供了一系列方法来对文件进行读取、写入等操作

一、打开文件的方法

python 提供open方法来打开文件

1 open方式打开文件

你在操作的过程中可能会忘了关闭文件而释放资源。那么我们可以通过下面的方式让python

自动关闭释放文件,它就是with ....open

通过这种方法,当执行完with语句后系统将自动释放打开的文件。

二 文件打开模式

对于open(filename,arg) 中文件打开模式arg参数有以下几种方式:

序号 参数 说明
1 r 只读
2 r+ 已读写的方式打开文件
3 w 已写入的方式打开文件,先删除文件原有内容,再写入新的内容。如果文件不存在,则创建一个新文件
4 w+ 已读写的方式打开文件,先删除文件原有内容,再写入新的内容。如果文件不存在,则创建一个新文件
5 a 已写入的方式打开文件,追加文件,不存在则创建一个新的文件
6 a+ 已读写的方式打开文件,追加文件,不存在则创建一个新的文件
7 b 已二进制模式打开文件,可与r,w,a一起结合使用
8 U 支持所有换行符,\n \r  \r\n 都表示换行

三 文件操作函数

文件读操作

1. read()           读取文件中的所有内容,返回结果为字符串<str>

int为读取的长度,在 python 3.x 中read()带参数是读取的为字符长度

python 3.x:

2. readlines()     读取文件的所有内容,返回结果为列表类型<list>

 with open(openfile, 'r') as f:
     a = f.readlines()
     print(type(a))
     print(a)
 结果:
 <class 'list'>
 [']  

3. readlines()    读取文件一行内容

4. tell()             返回当前指针在文件内容中的位置

5.seek(arg)       文件指针,arg参数为整型,代表在文件中的指针;seek(0) 文件开头,seek(1) 当前位置, seek(2)文件末尾

with open(openfile, 'r') as f:
    a = f.readline() # 读取一行内容
    print(a)
    print(f.tell())  # 现在指针的位置
    f.seek(0)   # 返回到文件开始位置
    a = f.readline()  # 又从头开始读了
    print(a)  

  注:seek方法对a, a+模式写文件时是不管用的,因为是追加模式,默认都会指向文件末尾

下面看一个实际应用例子,实现tail效果

 import time
 f = open('/home/ws/test','r')
 f.seek(2)<span style="white-space:pre">       </span># 定位到文件末尾
 while True:
     currline = f.tell()  # 获取当前位置
     line = f.readline()  # 读入内容
     if not line:         # 如果当前无信息
         f.seek(currline) # 继续定位在最末尾
     else:
         print(line)      # 输出内容
     time.sleep(2)  

四 文件写操作

6. write()           写文件,括号中的内容必须为str字符串类型,一次写入到文件中,如果字符串中有\n写入文件时也会换行

7. writeline()      写文件,除了可以写字符串类型外,还支持列表类型

8.truncate()      文件截断操作,将指针后面的所有内容截取掉

文件常用操作技巧:

1. 逐行读取文件内容

with open(openfile, 'r') as f:
    for line in f:
        print(line.strip())  

2. 使用stat 获取文件的信息

通过stat模块可以获取文件的一些基本信息

import os
import stat  

openfile = os.path.dirname(os.path.abspath("__file__")) + "\\README.md"
file_stat = os.stat(openfile) # return tuple
print("file_stat info: " ,file_stat)
print("file_stat mode: " , file_stat.st_mode)
print("check file is dir(stat): ", stat.S_ISDIR(file_stat.st_mode))
print("check file is file (os): ", os.path.isfile(openfile))
print("check file is file (stat):", stat.S_ISREG(file_stat.st_mode))
结果:
<span style="color:#ff6666;background-color: rgb(255, 255, 255);">file_stat info:  os.stat_result(st_mode=33206, st_ino=844424930202057, st_dev=2417903304, st_nlink=1, st_uid=0, st_gid=0, st_size=9, st_atime=1452135600, st_mtime=1452135607, st_ctime=1452135600)
file_stat mode:  33206
check file is dir(stat):  False
check file is file (os):  True
check file is file (stat): True</span>  

stat 模块常用函数:

stat.S_ISREG(st_mode)  == os.path.isfile(filename)  # 判断是否一般文件
stat.S_ISDIR(st_mode)  == os.path.isdir(filename)   # 判断是否为文件夹
stat.S_ISLNK(st_mode)  == os.path.islink(filename)   # 判断是否链接文件
stat.S_ISSOCK(st_mode)  # 判断是否套接字文件
stat.S_ISFIFO(st_mode)  # 判断是否命名管道
stat.S_ISBLK(st_mode)   # 判断是否块设备
stat.S_ISCHR(st_mode)   # 判断是否字符设置

stat 模块常用属性

openfile = os.path.dirname(os.path.abspath("__file__")) + "\\README.md"
file_stat = os.stat(openfile) # return tuple  

print("st_mode:", file_stat.st_mode)    # 权限模式
print("st_ino:", file_stat.st_ino)     # inode number
print("st_dev:", file_stat.st_dev)     # device
print("st_size:", file_stat.st_size)    # 文件的大小,以位为单位
print("uid:", file_stat.st_uid)     # 所有用户的user id
print("gid:", file_stat.st_gid)     # 所有用户的group id
print("st_atime:", file_stat.st_atime)   # 文件最后访问时间
print("st_mtime:", file_stat.st_mtime)   # 文件最后修改时间
print("st_ctime:", file_stat.st_ctime)   # 文件创建时间
结果:
st_mode: 33206
st_ino: 844424930202057
st_dev: 2417903304
st_size: 9
uid: 0
gid: 0
st_atime: 1452135600.2344666
st_mtime: 1452135607.5388844
st_ctime: 1452135600.2344666  

3 从一个文件写入到另一文件

 openfilepath = os.path.dirname(os.path.abspath("__file__"))
 file1 = openfilepath + "\\1.txt"
 file2 = openfilepath + "\\2.txt"
 with open(file1,'r') as f1,open(file2,'a+') as f2:
     f2.write(f1.read())  

Python系列-python文件操作的更多相关文章

  1. Python系列之文件操作、冒泡算法、装饰器、及递归

    文件处理 python对文件进行读写操作的方法与具体步骤,包括打开文件.读取内容.写入文件.文件中的内容定位.及关闭文件释放资源等 open().file(),这个两函数提供了初始化输入\输出(I\O ...

  2. python os&shutil 文件操作

    python os&shutil 文件操作 # os 模块 os.sep 可以取代操作系统特定的路径分隔符.windows下为 '\\' os.name 字符串指示你正在使用的平台.比如对于W ...

  3. python 历险记(三)— python 的常用文件操作

    目录 前言 文件 什么是文件? 如何在 python 中打开文件? python 文件对象有哪些属性? 如何读文件? read() readline() 如何写文件? 如何操作文件和目录? 强大的 o ...

  4. Python的高级文件操作(shutil模块)

    Python的高级文件操作(shutil模块) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 如果让我们用python的文件处理来进行文件拷贝,想必很多小伙伴的思路是:使用打开2个 ...

  5. Python入门篇-文件操作

    Python入门篇-文件操作 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.文件IO常用操作 open:打开 read:读取 write:写入 close:关闭 readlin ...

  6. python基础篇(文件操作)

    Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...

  7. Python之常用文件操作

    Python之常用文件操作

  8. python递归、collections系列以及文件操作进阶

    global log 127.0.0.1 local2 daemon maxconn log 127.0.0.1 local2 info defaults log global mode http t ...

  9. Python学习系列之文件操作

    Pyhton文件打开方式 with= open('文件路径','打开模式') as f:#PS:python3提供了with语句来帮我们自动调用close方法,所以说无论打开文件是否出错都能自动正确的 ...

随机推荐

  1. 如何配置springboot一访问服务器本地图片

    大家好,之前写过一篇配置tomcat访问服务器本地资源的,但现在使用了springboot内嵌tomcat\jeyyt后,怎么来访问本地资源呢? 打好springboot框架后,在applicatio ...

  2. 设计模式——享元模式(C++实现)

    #include <iostream> #include <string> #include <map> #include <vector> #incl ...

  3. Centos网口流量实时监控

    iptraf方式 [root@kazihuo ~]# yum -y install iptraf [root@kazihuo ~]# iptraf-ng-ng 开启服务日志: 进入细节监控后提示日志路 ...

  4. 笔记:Maven 设置代理配置

    如果公司基于安全因素考虑,要求使用通过安全认证的代理服务器访问因特网,这种情况夏,需要为 Maven 配置HTTP代理,才能让他正常访问外部仓库,配置代理服务器需要在~/.ms2/settings.x ...

  5. WEBLOGIC 11G (10.3.6) windows PSU 升级10.3.6.0.171017(Java 反序列化漏洞升级)

    10.3.6版本的weblogic需要补丁到10.3.6.0.171017(2017年10月份的补丁,Java 反序列化漏洞升级),oracle官方建议至少打上2017年10月份补丁. 一.查看版本 ...

  6. spring框架学习笔记4:SpringAOP实现原理

    AOP AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object Oriented Programming,面向对象编程)的补充和完善.OOP引入 ...

  7. winform 适配high dpi

    在 mainifest文件中添加:(新建mainifest文件的时候以下内容是有的,只要取消注释就可以了) <compatibility xmlns="urn:schemas-micr ...

  8. 第一部分 linux系统命令

    一.linux系统命令 pwd 当前目录位置 / 根目录 cd (change direcory) cd ..返回上一层目录 ls 显示当前目录下文件 ls -l 显示目录下详细文件信息 ls -lh ...

  9. 【iOS】OC-UTC日期字符串格式化

    NSLog(@"%@",[NSDate date]); NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init ...

  10. Visual Studio 开发工具常用的插件

    转载自落日故乡  http://www.spersky.com/post/vsPlugins.html 该博客中收集整理归纳了若干个常用的vs插件,比如高亮显示当前选择,垂直辅助线,折叠代码等等,具体 ...