python文件操作

简介:

1.file读文件


读取文件的步骤:

1.打开文件

2.文件操作(读或者写、替换replace)

3.关闭文件


例子:

import codecs   

file1 = codecs.open("1.txt")

print(file1.read())

file1.close()


说明:codecs 导入模块,解决文件乱码文件的类


2.file写文


写文件重要参数:

读取:r

写:w

二进制:b

追加:a


例子:

import codecs

file1 = codecs.open("1.txt","ab")

file1.write("This is the start\n")

file1.write("This is the end \n")

file1.close()


或者

import codecs

file1 = codecs.open("1.txt","ab")

file1.write("This is the {0}\n".format("start"))

file1.write("This is the %s\n" %"end")

file1.close()


3.file常用方法

readlines():读取所有文件,把文件每行的内容,作为字符串的元素,放在list中

例子:

import codecs

file1 = codecs.open("1.txt","rb")

print(file1.readlines())

file1.close()


readline():每次读取一行

例子:

import codecs

file1 = codecs.open("1.txt","rb")

print(file1.readline())

print(file1.readline())

file1.close()


next():读取文件下一行内容作为一个字符串

例子:

import codecs

file1 = codecs.open("1.txt","rb")

print(file1.readline())

print(file1.next())

file1.close()


write():必须写入一个字符串,和read()对应


writelines():必须写入一个字符串列表,和readines()对应

例子:

import codecs

list1 = ["a","b","c"]

file1 = codecs.open("example.txt","a")

file1.writelines(list1)


注:数字序列则报错,需强制转换类型,如str(i)


seek():定位光标移到某位置,例子中从光标位置开始写会覆盖原来全部内容

例子:

import codecs

file1 = codecs.open("1.txt","wb")

file1.seek(0)

file1.write("cc")

print(file1.tell())

file1.close()


其他的方法:

f.name    查看文件的名字

print f.closed     布尔值,判断文件是否关闭

print f.encoding()   查看文件的编码

f.mode    查看文件的打开模式

flush():刷新文件缓存



4.file的with用法


with:将1.txt赋值给f,再去操作f,这样写格式灵活,不需要考虑文件关闭的情况

例子:

import codecs

with codecs.open("1.txt","rb"as file1:

   print(file1.read())

   file1.close()


closed:判断是否关闭

例子:

import codecs

with codecs.open("1.txt","rb"as file1:

   print(file1.read())

   print(file1.closed)

   file1.close()

print(file1.closed)



enumerate:打印行号

例子:

import codecs

with codecs.open("1.txt","rb"as file1:

   for line,value in enumerate(file1):

       print(line,value)


linecache:从名为filename的文件中得到全部内容,输出为列表格式

例子:

import linecache

count = linecache.getline("1.txt",3)

print(count)










本文转自 huangzp168 51CTO博客,原文链接:http://blog.51cto.com/huangzp/1976937,如需转载请自行联系原作者
目录
相关文章
|
17天前
|
Python
Python文件操作学习应用案例详解
【4月更文挑战第7天】Python文件操作包括打开、读取、写入和关闭文件。使用`open()`函数以指定模式(如'r'、'w'、'a'或'r+')打开文件,然后用`read()`读取全部内容,`readline()`逐行读取,`write()`写入字符串。最后,别忘了用`close()`关闭文件,确保资源释放。
18 1
|
1月前
|
Unix Linux 测试技术
Python超详细基础文件操作(详解版)(下)
Python超详细基础文件操作(详解版)
|
1月前
|
存储 JSON 数据库
Python超详细基础文件操作(详解版)(上)
Python超详细基础文件操作(详解版)
|
1月前
|
Python
Python文件操作功能
Python文件操作功能
24 1
|
3月前
|
Python
掌握Python文件操作的绝招:打造数据之径,揭开文件操作的神秘面纱-2
掌握Python文件操作的绝招:打造数据之径,揭开文件操作的神秘面纱-2
|
3月前
|
Java Python
在Python中,进行文件操作
在Python中,进行文件操作
17 2
|
1月前
|
存储 安全 API
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
【Python 基础教程 21】Python3 文件操作全面指南:从入门到精通的综合教程
78 0
|
28天前
|
Python 存储
Python文件操作(六)
Python文件操作(六)
32 0
Python文件操作(六)
|
28天前
|
Python JSON 数据格式
08 Python之文件操作
08 Python之文件操作
41 0
|
1月前
|
存储 Java 程序员
【python】—— 文件操作
【python】—— 文件操作

热门文章

最新文章