Python 2 7 x 檔案操作的簡單示例

2021-06-24 18:04:58 字數 3539 閱讀 5605

讀檔案:

定義乙個簡單的文字處理函式:

def process(text):

print "process:", text

按位元組讀取:

def process(text):

print "process:", text

with open("tmp.txt") as f:

while true:

text = f.read(10)

if not text:

break

process(text)

按行讀取:

with open("tmp.txt") as f:

while true:

text = f.readline()

if not text:

break

process(text)

讀取所有內容,返回整個字串文字:
with open("tmp.txt") as f:

text = f.read()

process(text)

f.close()

讀取所有內容,返回乙個列表,列表的每個元素就是一行內容:

with open("tmp.txt") as f:

for line in f.readlines():

process(line)

fileinput懶惰行迭代:

當要讀取的檔案的非常大時,readlines會占有太多的記憶體,fileinput方法效能更好。

import fileinput

for line in fileinput.input("tmp.txt"):

process(line)

檔案迭代器(最佳實踐):

with open("tmp.txt") as f:

for line in f:

process(line)

寫檔案:write:

try:

with open("tmp.txt", "w") as f:

while true:

text = raw_input("please input: ")

if not text:

break

f.write(text)

except eoferror, e:

pass

writelines:

tmp_line = ["hello world", "hi python", "good bye"]

with open("tmp.txt", "w") as f:

# writelines並不會自動寫入換行符

f.writelines(tmp_line)

讀寫綜合(檔案拷貝示例cp.py):

from sys import argv

from sys import exit

if len(argv) != 3:

exit(1)

try:

with open(argv[1], "rb") as from_file, open(argv[2], "wb") as to_file:

while true:

tmp = from_file.read(1024)

if not tmp:

break

to_file.write(tmp)

except ioerror as err:

print "file error:", str(err)

序列化:

import cpickle as p

with open("tmp.dat", "w") as f:

with open("tmp.dat") as f:

print p.load(f)

隨機訪問:

# -*- coding: utf-8 -*- 

# seek(offset [, whence]) 把當前位置移動到由offset定義的位置。

# whence的值為0時(預設),表示相對位置是檔案開頭處;

# whence的值為1時,表示相對位置是當前位置;

# whence的值為2時,表示相對位置是檔案結尾處。

# tell方法返回當前檔案的位置。

with open("tmp.txt") as f:

print f.read(10)

print "pos:", f.tell()

f.seek(0)

print "pos:", f.tell()

print f.read()

print "pos:", f.tell()

os.path模組:

遍歷目錄:

# -*- coding: utf-8 -*- 

import sys

import os

def formate_filename(filename, deep = 0):

tab = ''

d = 0

while d < deep:

tab += ' '

d += 1

return tab + os.path.basename(filename)

def list_dir(dirname, deep = 0):

if not os.path.exists(dirname):

print dirname, 'is not existed'

sys.exit(1)

if os.path.isfile(dirname):

print formate_filename(dirname, deep)

if os.path.isdir(dirname):

print formate_filename(dirname, deep) + ":"

# 列出目錄的所有檔案和子目錄

filenames = os.listdir(dirname)

for filename in filenames:

list_dir(dirname + os.sep + filename, deep + 1)

if len(sys.argv) < 2:

sys.exit(1)

del sys.argv[0]

for dirname in sys.argv:

list_dir(dirname)

print

CentOS 6 X更新Python2 7 X版本

centos 6.x自帶預設python版本為2.6.6。但由於工作需要,很多時候需要2.7版本,所以需要進行版本公升級 步驟如下 使用 python v 查詢本機python系統 再安裝新版之前安裝 先安裝bz2 zlib,執行下列 進行安裝 yum install y zlib devel bz...

Python的檔案操作

1.open使用open開啟檔案後一定要記得呼叫檔案物件的close 方法。比如可以用try finally語句來確保最後能關閉檔案。file object open thefile.txt try all the text file object.read finally file object....

Python的檔案操作

python中對檔案 資料夾 檔案操作函式 的操作需要涉及到os模組和shutil模組。一 1.得到當前工作目錄,即當前python指令碼工作的目錄路徑 os.getcwd 2.返回指定目錄下的所有檔案和目錄名 os.listdir 3.函式用來刪除乙個檔案 os.remove 4.刪除多個目錄 o...