python 中文件輸入輸出及os模塊對文件系統的操做

整理了一下python 中文件的輸入輸出及主要介紹一些os模塊中對文件系統的操做。python

文件輸入輸出

一、內建函數open(file_name,文件打開模式,通用換行符支持),打開文件返回文件對象。ios

二、對打開文件進行讀取時,readline()readlines()的區別在因而否一次性的讀取全部的內容,並將每行的信息做爲列表中的一個子項。
例如:文件test.txt中函數

1,3,4
  2,35,6

分別用readline與readlines對其進行讀取ui

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

三、文件迭代
使用迭代器的file.next()用於讀取文件的下一行。相比for循環,更復雜,通常採用 for循環直接迭代。spa

四、文件移動
seek(off,whence=0)能夠在文件中移動文件指針到不一樣的位置,,從文件中移動off個操做標記(文件指針),正往結束方向移動,負往開始方向移動。若是設定了whence參數,就以whence設定的起始位爲準,0表明從頭開始,1表明當前位置,2表明文件最末尾位置。
tell()能夠展現 咱們的移動過程,展現咱們的當前位置操作系統

五、os模塊指針

六、文件寫入f.write()writelines()接受一個字符串列表做爲參數
須要手動輸入換行符\n;code

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模塊

相關文章
相關標籤/搜索