python 中文件输入输出及os模块对文件系统的操作

整理了一下python 中文件的输入输出及主要介绍一些os模块中对文件系统的操作。

文件输入输出

1、内建函数open(file_name,文件打开模式,通用换行符支持),打开文件返回文件对象。

2、对打开文件进行读取时,readline()readlines()的区别在于是否一次性的读取所有的内容,并将每行的信息作为列表中的一个子项。
例如:文件test.txt中

  1,3,4
  2,35,6

分别用readline与readlines对其进行读取

r=file_object.readline();
#结果为1,3,4
r=file_object.readlines();
#结果为['1,3,4\n', '2,35,6']

3、文件迭代
使用迭代器的file.next()用于读取文件的下一行。相比for循环,更复杂,一般采用 for循环直接迭代。

4、文件移动
seek(off,whence=0)可以在文件中移动文件指针到不同的位置,,**从文件中移动off个操作标记(文件指针),正往结束方向移动,负往开始方向移动。如果设定了whence参数,就以whence设定的起始位为准,0代表从头开始,1代表当前位置,2代表文件最末尾位置。 **
tell()可以展示 我们的移动过程,展示我们的当前位置

5、os模块

6、文件写入f.write()writelines()接受一个字符串列表作为参数
需要手动输入换行符\n;

fobj=open('test','w');#直接在指定路径下打开test1 ,如果没有则直接生成,但若存在,则出错;
fobj.write('foo\n');
fobj.write('bar\n');
fobj.close();
#结果为
#foo
#bar
import os;
file_object=open(r'E:\Python\iostream_test\test.txt','r+');
aline=raw_input("Enter a line ('.'to quit):");
if aline !=".":
    file_object.write('%s%s' % (aline,os.linesep));
#在文件test.txt中写入一条字符串结果为txt 文件中的一个内容

标准文件

一般程序一执行,就可以访问3个标准文件,分别是标准输入(一般是键盘)、标准输出(到显示器的缓冲输出)和标准错误(到屏幕的非缓冲输出),这里的缓冲、非缓冲是指open()的三个参数。

文件系统

对文件系统的访问大多通过python的os模块实现。该模块是python访问操作系统功能的主要接口。

os除了对进程和进程运行环境进行管理外,os模块还负责处理大部分的文件系统操作,包括删除/重命名文件,遍历目录树,已经管理文件访问权限等。

另一个os.path 模块可以完成针对路径名的操作,它提供函数 完成管理和操作文件路径中的各个部分,获取文件或者子目录信息,文件路径查询等操作。

针对os path的操作,操作对象E:\Python\iostream_test文件及其下的test.txt文件

os.path.exists(),检测指定路径的文件或者目录是否存在。

import os;
for tempdir in ('/test.txt',r'E:\Python\iostream_test\test.txt'):
  if os.path.exists(tempdir):
      print 'yes';
      break;
else:
    print 'no temp directory available';
    tempdir=' ';
#结果为yes,
# 若in中改为('/test.txt',r'D:\Python\iostream_test\test.txt'),则结果为no temp directory available

os.path.isdir(),检测指定了路径是否存在且为一个目录,只能是目录,否则报错。

import os;
for tempdir in ('/test.txt',r'E:\Python\iostream_test\test.txt'):
 #in中检测的是文件,而非目录,所以未输出yes
  if os.path.isdir(tempdir):
      print 'yes';
      break;
else:
    print 'no temp directory available';
    tempdir=' ';
# 输出no temp directory available
import os;
for tempdir in ('/test.txt',r'D:\Python\iostream_test\test.txt'):
#指定路径在D盘,因而不存在
  if os.path.isdir(tempdir):
      print 'yes';
      break;
else:
    print 'no temp directory available';
    tempdir=' ';
import os;
for tempdir in ('/test.txt',r'E:\Python\iostream_test'):
 if os.path.isdir(tempdir):
     print 'yes';
     break;
else:
   print 'no temp directory available';
   tempdir=' ';
#输出的是yes

同理可得os.path.isfile()只可检测指定路径是否存在且为一个文件

以下针对os中某些进行练习,针对文件的操作,因先检测是否存在指定路径,再对该路径或者路径中的文件做操作。更多的练习可以看read.md

import os;
for tempdir in ('/tmp',r'E:\Python\iostream_test'):
  if os.path.isdir(tempdir):#检测指定路径是否存在且为一个目录,并赋给tempdir
      print 'yes';
      break;
else:
    print 'no temp directory available';
    tempdir=' ';

if tempdir:
    os.chdir(tempdir); #改变当前工作路径
    cwd=os.getcwd(); #获取当前工作路径;
    print 'current temporany directory is :';
    print cwd;
    print os.listdir(cwd);
    
    print 'creating example directory';
    os.mkdir('example'); #在当前目录下新建一个新的文件
    os.chdir('example'); #改变目录到example的文件下
    cwd=os.getcwd();#获取example的文件路径
    print 'new working directory:'
    print cwd;
    print ' original directory listing :'
    print os.listdir(cwd);#列出(example)指定路径下的文件
    os.chdir(tempdir);
    cwd=os.getcwd(); 
    print os.listdir(cwd);#列出(tempdir)指定路径下的文件
# 结果为:
# current temporany directory is :
# E:\Python\iostream_test
# ['pspathex.py', 'read.md', 'read.py', 'test.txt']
# creating example directory
# new working directory:
# E:\Python\iostream_test\example
#  original directory listing :
# []
# ['example', 'pspathex.py', 'read.md', 'read.py', 'test.txt']

os.path.join()方法将分离的各部分组合成一个路径名

 path=os.path.join(cwd,os.listdir(cwd)[0]);
 print ' full file pathname:'
 print path;
 #结果为E:\Python\iostream_test\example\filetest.txt

os.path.split(path)方法将组合路径分成(路径名,文件名)

path=os.path.join(cwd,os.listdir(cwd)[0]);
print os.path.split(path);#(pathname,basename)
#结果为('E:\\Python\\iostream_test\\example', 'filetest.txt')

os.path.splitext(os.path.basename(path))方法将文件分成(文件名,文件扩展名)

path=os.path.join(cwd,os.listdir(cwd)[0]);
print os.path.splitext(os.path.basename(path));#(filename,extension)
#结果为('filetest', '.txt')

相关模块

永久存储模块,永久存储数据:pickle 、marshal模块、DBM风格模块、shelve模块

posted @ 2018-08-27 15:54  msay  阅读(889)  评论(0编辑  收藏  举报