談談python的文件處理——文件的輸入與輸出


簡單介紹一下python里IO的幾種常用方式。當然除了以下介紹的幾種方式之外,還可以參考python的手冊,例如我想查找raw_input函數的用法,我就可以直接使用命令:python -m pydoc raw_input(windows底下)來查看使用方法,使用完畢時候,輸入“q”作為退出。下面進入正題:

一、python中的輸入

1.從命令行中完成輸入(與命令行的“博弈”——raw_input函數)

 

#Input:

age = raw_input("How old are you? ")

height = raw_input("How tall are you? ")

weight = raw_input("How much do you weigh? ")

print "So, you're %r old, %r tall and %r heavy." % (age, height, weight) #一種輸出變量內容的方式

 

#Output:

How old are you? 35

How tall are you? 6'2"

How much do you weight? 180lbs

So, you're '35' old, '6\'2"' tall and '180lbs' heavy.

注意:這里 %r 是 debug 專用,它顯示的是原始表示出來的字符;也會常常見到使用%s的情況, %s 是為了顯示給用戶看的字符串。

 

2.傳遞參數給代碼(來自參數的“閱讀”——將變量傳遞給腳本)

#Input:

from sys import argv

script, first, second, third = argv

print "The script is called:", script

print "Your first variable is:", first

print "Your second variable is:", second

print "Your third variable is:", third

 

#Output:

 python ex13.py cheese apples bread

The script is called: ex13.py

Your first variable is: cheese

Your second variable is: apples

Your third variable is: bread

 

 

3.文件讀取(傾聽文件的“內容”——讀取文件有妙招)

 

假設我們現在有兩個文件,一個是腳本文件 ex.py ,另外一個是 ex_sample.txt,第二

個文件是供你的腳本讀取的文本文件。假設第二個文件的內容:

This is stuff I typed into a file.

It is really cool stuff.

Lots and lots of fun to have in here.

我們要做的是把該文件用我們的腳本“打開(open)”,然后打印出來。然而把文件名

ex_sample.txt 寫死(hardcode)在代碼中不是一個好主意,這些信息應該是用戶輸入的才對。如果我們碰到其他文件要處理,寫死的文件名就會給你帶來麻煩了。我們的解決方案是使用 argv raw_input 來從用戶獲取信息,從而知道哪些文件該被處理。

 

#Input:

from sys import argv

script, filename = argv

txt = open(filename)

print "Here's your file %r:" % filename

print txt.read()

 

#Output:

python ex.py ex_sample.txt 

Here's your file 'ex_sample.txt':

This is stuff I typed into a file.

It is really cool stuff.

Lots and lots of fun to have in here.

 

 

延伸:txt = open(filename) 返回的是文件的內容嗎? 不是,它返回的是一個叫做“file object”的東西,你可以把它想象成一個磁帶機或者 DVD 機。你可以隨意訪問內容的任意位置,並且去讀取這些內容,不過這個 object 本身並不是它的內容。

 

 

二、讀寫文件

1.常用讀寫文件函數——韓信點兵:

 

• close – 關閉文件。跟你編輯器的 文件->保存.. 一個意思。 

• read – 讀取文件內容。你可以把結果賦給一個變量。 

• readline – 讀取文本文件中的一行。 

• truncate – 清空文件,請小心使用該命令。 

• write(stuff) – 將 stuff 寫入文件。 

清空文件,並重寫文件  

Example

print "Opening the file..."

target = open(filename, 'w')

print "Truncating the file. Goodbye!"

target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")

line2 = raw_input("line 2: ")

line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write(line1)

target.write("\n")

target.write(line2)

target.write("\n")

target.write(line3)

target.write("\n")

print "And finally, we close it."

target.close()

 

 

2.其他文件操作——八仙過海,各顯神通

 

文件拷貝

Example

from sys import argv

from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line too, how?

in_file = open(from_file)

indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)

print "Ready, hit RETURN to continue, CTRL-C to abort."

raw_input()

out_file = open(to_file, 'w')

out_file.write(indata)

print "Alright, all done."

out_file.close()

in_file.close()

 

 

文件和函數相結合

Example

from sys import argv

script, input_file = argv

def print_all(f):

print f.read()

def rewind(f):

f.seek(0)

def print_a_line(line_count, f):

print line_count, f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tape."

rewind(current_file)

print "Let's print three lines:"

current_line = 1

print_a_line(current_line, current_file)

current_line = current_line + 1

print_a_line(current_line, current_file)

current_line = current_line + 1

print_a_line(current_line, current_file)

 

 

 

 其中seek(0),表示找到文件開始的位置。這里重點強調下容易犯的錯誤:有的時候,對於同一個文件我們可能需要讀取使用兩次,由於第一次讀取文件時,文件的指針會隨着讀取的內容移動,因此在第一次讀取完文件后,文件的指針會在文件結束的位置。想要第二次讀取文件的話,如果不對指針制定位置或者重置,就會出現讀取的文件內容為空的情況。舉一個例子來說:

    f = open(filename, 'r')
    bodylist=[ line for line in f] 
    messagelist=[line for line in f]

如果按照上述方式進行的話,那么返回的結果將是:bodylist=["line1 content","line2 content","" .....]  messagelist=[] ;出現了文件在第二次讀取時為空的現象!!想要得到正確的結果的話,只需要使用seek(0),使得文件的指針再次從頭開始。其中參數0指的意思是:從文件開頭處開始索引。因此好的方式是寫成:

    f = open(filename, 'r')
    bodylist=[ line for line in f] 
    seek(0)
    messagelist=[line for line in f]

這樣便可以得到正確的結果:bodylist=["line1 content","line2 content","" .....]  messagelist=["line1 content","line2 content","" .....]

 三、和文件夾有關的操作

1.如何羅列出一個文件夾下的所有文件?這里列舉四個方法,主要通過os模塊、glob模塊來實現的。

 

#方法1:使用os.listdir
import os
for filename in os.listdir(r'c:\windows'):
    print filename
 
#方法2:使用glob模塊,可以設置文件過濾
import glob
for filename in glob.glob(r'c:\windows\*.exe'):
    print filename
 
#方法3:通過os.path.walk遞歸遍歷,可以訪問子文件夾
import os.path
def processDirectory ( args, dirname, filenames ):
    print 'Directory',dirname
    for filename in filenames:
        print ' File',filename
 
os.path.walk(r'c:\windows', processDirectory, None )
 
#方法4:非遞歸方法
import os
for dirpath, dirnames, filenames in os.walk('c:\\windows'):
    print 'Directory', dirpath
    for filename in filenames:
        print ' File', filename

2.判斷某個文件和目錄是否存在

import os
os.path.isfile('test.txt') #如果不存在就返回False
os.path.exists(directory) #如果目錄不存在就返回False

 

3.如何查找一個文件夾里最新產生的文件

# -*- coding:UTF-8 -*-
import os,os.path,datetime
base_dir="c:\\Windows\\"
l=os.listdir(base_dir)
l.sort(key=lambda fn: os.path.getmtime(base_dir+fn) if not os.path.isdir(base_dir+fn) else 0)
d=datetime.datetime.fromtimestamp(os.path.getmtime(base_dir+l[-1]))
print('最后改動的文件是'+l[-1]+",時間:"+d.strftime("%Y年%m月%d日 %H時%M分%S秒"))

 

 

附加:多行輸出的方法

print """

Alright, so you said %r about liking me.

You live in %r. Not sure where that is.

And you have a %r computer. Nice.

""" % (likes, lives, computer)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM