您的位置:首页 > 编程语言 > Python开发

谈谈python的文件处理——文件的输入与输出

2014-10-14 11:11 423 查看
简单介绍一下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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: