python ##1 Python中的文件管理方式,os的使用

python文件的概念

文件:Python中文件是对象;

Linux文件:一切设备都可以看成文件

例如:磁盘文件,管道,网络socket,外设等

文件属性:用户,读,写,执行权限

 

Python文件打开方式

文件打开方法:open(name[,mode[buf]])

name: 文件路径

mode打开方式

buf:   缓冲buffering大小

 

Python 读取方式

文件读取方式:

read([size]):读取文件(读取size个字节,默认读取全部)

readline([size]):读取一行

readlines([size]):读取完文件,返回每一行所组成的列表

弊端当打开文件很大时,占用的内存比较大

iter迭代器

 

Python写入方式

文件写入方式:

writestr:将字符串写入文件

writelinesequence_of_strings:写多行到文件,参数为可迭代的对象

 

Linux下创建并执行Python脚本

vim first.py

 #! /usr/bin/env python    

list = [ 1,2,3,4,5,6,7,9,10,11]  

tuple = (1,2,3,4,5,6,7,9,10)  

print list  

print tupl


执行py脚本 

python first.py   

Python文件打开方式

In [1]: ls

cifar-10-batches-py/  hello.py  Untitled.ipynb  股票收盘价格的预测.ipynb

 

In [2]: f = open("hello.py")

 

In [3]: type(f)

Out[3]: _io.TextIOWrapper

 

In [4]: c = f.read()

 

In [5]: c

Out[5]: "#!/usr/bin/env python\nprint ('hello world')\n"

In [8]: f = open("1.txt",'w')

 

In [9]: f.write("test wirte")

Out[9]: 10

 

In [10]: f.close()

In [13]: f = open("1.txt",'w')

 

In [14]: f.close()

 

In [15]: cat 1.txt

 

In [16]: f= open("hello.py",'a')

#以追加的方式打开文件

In [17]: f.write("print ('write test')")

Out[17]: 20

 

In [18]: f.close()

 

In [19]: cat hello.py

#!/usr/bin/env python

print ('hello world')

print ('write test')

In [20]: f =  open('hello.py','r+')

 

In [21]: f.write("test r+")

Out[21]: 7

 

In [22]: f.close()

 

In [23]: cat hello.py

test r+bin/env python

print ('hello world')

print ('write test')

 

迭代器的使用

In [7]: f.close()

 

In [8]: f = open('imooc.txt')

 

In [9]: iter_f = iter(f)

 

In [10]: lines = 0

 

In [11]: for line in iter_f:

    ...:     lines+=1

    ...:    

 

In [12]: lines

Out[12]: 3017

 

Python写磁盘时机

1:主动调用close()或者flush方法,写缓存同步到磁盘上

2:写入数据量大于或者等于写缓存,写缓存同步到磁盘;

 

Python文件为什么要关闭

1:将写缓存同步到磁盘;

2:Linux系统中每个进程打开文件的个数是有限的

3:如果打开文件数到了系统限制,再打开文件就会失败;

 

Python写入和读取问题

1、写入文件后,必须打开才能读取写入内容

2、读取文件后,无法重新再次读取读过的内容

Python文件指针

Python文件指针定位方式:

os.SEEK_SET:相对文件起始位置

os.SEEK_CUR:相对文件当前位置

os.SEEK_END:相对文件结尾位置

 

In [1]: f = open('imooc.txt','r+')

 

In [2]: import os

 

In [3]: f.tell()

Out[3]: 0

 

In [4]: help(f.tell)

 

 

In [5]: f.read(3)

Out[5]: 'tes'

 

In [6]: f.tell()

Out[6]: 3

 

In [7]: f.seek(0,os.SEEK_SET)

Out[7]: 0

 

In [8]: f.tell()

Out[8]: 0

 

In [9]: f.read(3)

Out[9]: 'tes'

 

In [10]: f.seek(0,os.SEEK_END)

Out[10]: 148890

 

Python文件属性

file.fileno():文件描述符

file.mode:文件打开权限

file.encoding:文件编码格式

file.closed:文件是否关闭

 

Python标准文件

文件标准输入:sys.stdin

文件标准输出:sys.stdout

文件标准错误:sys.stderr

 

Python文件命令行参数

我们执行程序,如果能根据参数不同完成不同的功能

sys模块提供sys.argv属性,通过该属性可以得到命令行参数

sys.argv:字符串组成的列表

import sys

if __name__ == '__main__':

        print (len(sys.argv))

        for arg in sys.argv:

                print (arg)

 

Python文件编码格式

使用普通方式打开文件:写入u’慕课’,出现什么问题

将uincode转换为utf-8文件格式

使用codeces模块提供方法创建指定编码格式文件

import codecs

open(fname,mode,encnding,errors,buffering):

 

In [17]: import codecs

 

In [18]: help(codecs.open)

 

 

In [19]: f = codecs.open('text.txt','w','utf-8')

 

In [20]: f.encoding

Out[20]: 'utf-8'

 

In [21]: f.write(u'慕课)

 

Python3的变化

  1. print 由一个语句(statement)变为一个函数
  2. Python3中的 str 类型现在是原来的 unicode 类型,而原 str 类型现在是 bytes
  3. 由第 2 条,uincode() 函数被移除,功能由 str()取代,而原 str() 由 bytes() 取代
  4. 长整型(long)和整型(int)统一为整形(int)
  5. 不再支持 <> 比较运算符号,仅支持 !=
  6. 字典(dict)对象的 has_key() 方法被移除,仅支持 in 操作
  7. 许多字典(dict)类方法返回值是列表的变为动态视图(dynamic view),视图(view)不支持索引操作
  8. 几个相关的 HTTP 模块被组合为一个单独的包,即 http
  9. 包内的相对导入
  10. 定义新的全局函数 next() ,它使用一个迭代器作为参数
  11. filter() 函数返回一个迭代器(iterator)而不是列表(list)
  12. map() 函数返回一个迭代器(iterator)而不是列表(list)
  13. reduce() 不再是全局函数,它现在被放在 functools 模块里
  14. apply() 函数被移除
  15. intern() 不再是全局函数,它现在被放在 sys 模块里
  16. exec 由一个语句变为一个函数

linux文件系统简介

文件包括:磁盘(ext2,ext4)文件,NFS文件系统,各种外设(SD卡,USB设备)等

Linux如何来管理外设,为应用层提供统一接口?

使用os模块打开文件

os.open(filename,flag[,mode]):打开文件

flag:打开文件方式

         os.O_CREAT:创建文件

         os.O_RDONLY:只读方式打开

         os.O_WRONLY:只写方式打开

         os.O_RDWR:读写方式打开

 

os.read(fd,buffersize):读取文件

os.write(fd,string):写入文件

os.lseek(fd,pos,how):文件指针操作

os.close(fd):关闭文件

 

In [15]: os.access('imooc1.txt',os.R_OK)

Out[15]: True

 

In [16]: os.access('imooc1.txt',os.W_OK)

Out[16]: True

 

In [17]: os.access('imooc1.txt',os.X_OK)

Out[17]: True

 

 

Python文件练习

练习内容:

使用Python管理ini文件:实现查询,添加,删除,保存

练习目的:

1.掌握文件基本操作

2.认识ini文件

3.了解ConfigParser

ini配置文件格式:

节: [session]

参数: name = value

例子 [port]

         port1 = 8000

         port2= 8200

 

import configparser

cfg = configparser.ConfigParser()

cat imooc.txt

cfg.read('imooc.txt')

cfg.sections()

for se in cfg.sections():

    print (se)

    print (cfg.items(se))

cfg.set('user info','pwd','123456')

for se in cfg.sections():

    print (se)

    print (cfg.items(se))

cfg.set('user info','email','[email protected]')

for se in cfg.sections():

    print (se)

    print (cfg.items(se))

cfg.remove_option('user info','email')

for se in cfg.sections():

    print (se)

    print (cfg.items(se))

猜你喜欢

转载自blog.csdn.net/u010104301/article/details/85152301
今日推荐