Python对文件操作知识汇总
Jun 10, 2016 pm 03:04 PM打开文件
操作文件
1打开文件时,需要指定文件路径和打开方式
打开方式:
r:只读
w:只写
a:追加
“+”表示可以同时读写某个文件
r+:读写
w+:写读
a+:同a
U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
rU
r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
rb
wb
ab
1 2 3 4 5 6 7 8 |
|
二:常见的文件运算
f = open('data', 'r') #以只读形式打开(默认就是只读)
f = open('f.txt', encoding='latin-1') #python3.0 Unicode文件
string = f.read() #把文件读入一个字符串中
string = f.read(N) #读取指针后的N个字节
string = f.readline() #读取下一行,包括行末标识符
alist = f.readlines() #读取整个文件到字符串列表
f.write() #将字符串写入文件
f.writelines() #将列表内所有字符串写入文件
f.close() #手动关闭
f.flush() #把输出缓冲区刷到硬盘中
f.seek(N) #将文件指针移到N处,以字节为单位
for line in open('data'):
print(line) #文件迭代器将文件一行行读出
open('f.txt','r').read() #read all at ance into string
三:在文件中存储并解析python对象
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 |
|
以上所述是小编给大家介绍的Python对文件操作知识汇总的相关知识,希望对大家有所帮助!

Article chaud

Outils chauds Tags

Article chaud

Tags d'article chaud

Bloc-notes++7.3.1
Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise
Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1
Puissant environnement de développement intégré PHP

Dreamweaver CS6
Outils de développement Web visuel

SublimeText3 version Mac
Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Sujets chauds

Comment utiliser la belle soupe pour analyser HTML?

Comment utiliser Python pour trouver la distribution ZIPF d'un fichier texte

Comment effectuer l'apprentissage en profondeur avec TensorFlow ou Pytorch?

Introduction à la programmation parallèle et simultanée dans Python

Sérialisation et désérialisation des objets Python: partie 1

Comment implémenter votre propre structure de données dans Python

Modules mathématiques en python: statistiques
