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

python程序设计基础5:python文件使用(遍历一个文件夹中所有的图片)

2014-03-29 14:15 981 查看
文件的操作是非常常用的。下面通过基本的例子了解对一般的TXT文档的操作。

1.创建一个TXT文本,在其中写入学生的基本信息。包括:姓名,性别,地址4个信息。

代码:

11 #!/usr/bin/env python

 10 # encoding: utf-8

  9                                            

  8 f=open('filecreat.txt','w')

  7 f.write('name'+'\tsex'+'\tcellphone'+'\t\taddress'+'\n')

  6 flag=1

  5 while flag==1:

  4     name=raw_input('please input a name:')

  3     sex=raw_input('please input the sex:')

  2     cellphone=raw_input('please input the cellphone number:')

  1     address=raw_input('please input the address:')

12      s=name+'\t'+sex+'\t'+cellphone+'\t\t'+address+'\n'                                                  

  1     f.write(s)

  2     flag=input('will you go on?(1/0):')

 3 f.close()

结果:

please input a name:iker

please input the sex:man

please input the cellphone number:123456789

please input the address:XMU

will you go on?(1/0):1

please input a name:456123

please input the sex:UESTC

please input the cellphone number:1234567894

please input the address:xsf

will you go on?(1/0):0

ikerpeng@~/text/mlexcersise$ python excersice2.py 

name sex
cellphone address

iker man
123456789 XMU

456123 UESTC1234567894xsf

2,读出1中生成的文件

代码:

 4 f=open('filecreat.txt','r')

  5 while True:

  6     line=f.readline()

  7     if line=='':

  8         break

  9     print line

 10 f.close()  

结果:

name sex
cellphone address

iker man
123456789 XMU

456123 UESTC
1234567894 xsf

3,文本文件的读取主要有三个命令:read(),readline(),readlines()。其中,read(n)表示读出前n个字节。readline()表示读出一行的内容,readlines()读出文件的每一行内容。下面的例子。

代码:

 8 #!/usr/bin/env python

  7 # encoding: utf-8

  6  

  5 f=open('filecreat.txt','r')

  4 line=f.readline()

  3 n=len(line)

  2 print n

  1 print line

9   line2=f.readlines()                                                                                     

  1 m=len(line2)

  2 print line2,m

  3 line3=f.read(5)

  4 print line3

  5 f.close()

结果:

28

name sex
cellphone address

['iker\tman\t123456789\t\tXMU\n', '456123\tUESTC\t1234567894\t\txsf\n'] 2

看了上面的代码结果,你会觉得有点奇怪。事实上是和这三个函数放的位置是有关系的。放在前面的line=f.readline()读出了文件中的第一行,所以ine2=f.readlines()   是从第二行开始的。但是这个命令他会读完整个文件,所以后面的line3=f.read(5)就没有起到任何作用了。

3,二进制文件的存取。python本身的struct和pickle模块里面就有关于二进制的操作。详细情况课参见《计算机编程导论——python程序设计》。但是我鼻尖推荐的是numpy这个包里面的几个很直观的函数详见:http://blog.csdn.net/ikerpeng/article/details/20127747。下面还是从几个例子来说明。

4、编写一个复制文件的函数:

代码:

f=open('aa.txt','r')

f2=open('refile.txt','w')

s=f.read()

f2.write(s)

f2.close()

f2=open('refile.txt','r')

line=f2.readlines()

for i in line:

    print i

f.close()

f2.close()

结果:

a is your key!

and  do you like her?

maybe 

but don't come true as my will ,as your will,my father!

若是写成一个函数的形式:

def copy(srcfile,refile):

    try:

        f=open(srcfile,'r')

        f2=open(refile,'w')

    except:

        print'the open progress is failed'

        return -1

    s=f.read()

    f2.write(s)

    f.close()

    f2.close()

    return 0

copy('aa.txt','refile.txt')

f=open('refile.txt','r')

line=f.readlines()

for l in line:

    print l

得到的结果和上面是一样的。

5、生成一个TXT文件,向里面写入各种字符,统计里面的大小写字母、数字以及其他类型的个数。

代码:

f=open('a.txt','w')

s='''dsadksa dsak gfke dfe DWSwwWSE dwEWF 349*^% &%)'KAD ++"" '''

f.write(s)

f.close()

f=open('a.txt','r')

nupper=0

nlower=0

ndigit=0

nrest=0

while True:

    x=f.read(1)

    if x=='':

        break

    elif x.isupper():

        nupper=nupper+1

    elif x.islower():

        nlower=nlower+1

    elif x.isdigit():

        ndigit=ndigit+1

    else:

        nrest=nrest+1

f.close()

print'nupper=',nupper

print'nlower=',nlower

print'ndigit=',ndigit

print'nrest=',nrest

结果:

nupper= 12

nlower= 22

ndigit= 3

nrest= 20

需要注意的是代码中的while循环,他是如何结束的。 x=f.read(1)表示每次读一个字符,当下一个循环来的时候就从下一个字符开始读取了!读到末尾的时候就跳出循环了。

6、建立一个文件,写人含有“hello”字符的文字。然后用hi替换里面的hello。

代码:

f=open('a.txt','w')

s='''hello world we say hello at the first time

but don't you know i am not justa hello friends

maybe someday i will be your hello and you will be my father!

Hello hello '''

f.write(s)

f.close()

f=open('a.txt','r')

f2=open('ab.txt','w+')

while True:

    x=f.read(5)

    point=f.tell()

    if len(x)<5:

        break

    if x=='hello':

        f2.write('hi')

    else:

        f2.write(x[0])

        f.seek(point-4)

f.close()

f2=open('ab.txt','r')

s=f2.read()

f2.close()

print s

结果:

hi world we say hi at the first tm

but don't you know i am not justa hi fried

maybe someday i will be your hi and you will be my fathr

Hello hi

7、生成一个二进制文件,保存学生的成绩信息

代码:

import struct

f=open('a.dat','w')

n=input('please input the number of the student:')

s=struct.pack('i',n)

f.write(s)

s2='number      name    gaoshu    xiandai    computer  '

print 'len(s2)=',len(s2)

f.write(s2)

i=0

while i<n:

    num=input('please input the number:')

    name=input('please input the name:')

    a1=input('please input the score of gaoshu:')

    a2=input('please input the score of xiandai:')

    a3=input('please input the score of computer:')

    s=num+name

    s=s+struct.pack('fff',a1,a2,a3)

    f.write(s)

    i=i+1

f.close()

结果:

please input the number of the student:2

len(s2)= 51

please input the number:'123456789'

please input the name:'iker'

please input the score of gaoshu:89

please input the score of xiandai:56

please input the score of computer:97

please input the number:'456789123'

please input the name:'peng'

please input the score of gaoshu:84

please input the score of xiandai:85

please input the score of computer:79

遍历一个文件夹中所有的图片:

import os
def get_imlist(path):
"""    Returns a list of filenames for
all jpg images in a directory. """

return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.jpg')]

filelist = get_imlist('path')


简单的还可以这样:

import os
for f in os.listdir('path'):
print f

这两个非常有用!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python