filename = "test_file.txt"
def write_file():
f = open(filename, 'w')
f.write('hello ithomer')
f.write('\n')
f.write('my blog: http://blog.ithomer.net')
f.write('\n')
f.write('this is the end')
f.write('\n')
f.close()
def read_file():
f = open(filename, 'r')
line = f.readline()
while line:
print line
line = f.readline()
f.close()
if __name__ == "__main__":
write_file()
read_file()
运行结果: hello ithomer
my blog: http://blog.ithomer.net
this is the end
'''
======== output result =========
read()
hello world
my blog is ithomer.net
this is end.
readline() f.seek(0)
hello world
readline() f.seek(1)
12
1
ello world
readline() f.seek(10)
12
10
d
12
my blog is ithomer.net
readline() f.seek(15)
35
15
blog is ithomer.net
35
this is end.
readlines()
['hello world\n', 'my blog is ithomer.net\n', 'this is end.\n']
list all lines
readlines()
['hello world\n', 'my blog is ithomer.net\n', 'this is end.\n']
list all lines
hello world
my blog is ithomer.net
this is end.
seek(15) function
tell() function
15
blog is ithomer.net
this is end.
'''
# -*- coding:utf-8 -*-
import re
import os
import time
#str.split(string)分割字符串
#'连接符'.join(list) 将列表组成字符串
def change_name(path):
global i
if not os.path.isdir(path) and not os.path.isfile(path):
return False
if os.path.isfile(path):
file_path = os.path.split(path) #分割出目录与文件
print(file_path)
lists = file_path[1].split('.') #分割出文件与文件扩展名
file_ext = lists[-1] #取出后缀名(列表切片操作)
img_ext = ['bmp','jpeg','gif','psd','png','jpg']
if file_ext in img_ext:
path2 = file_path[0]+'/'+lists[0]+'_fc.'+file_ext
os.rename(path, path2)
print("old = %s" % path)
print("new = %s" % path)
i+=1 #注意这里的i是一个陷阱
#或者
#img_ext = 'bmp|jpeg|gif|psd|png|jpg'
#if file_ext in img_ext:
# print('ok---'+file_ext)
elif os.path.isdir(path):
for x in os.listdir(path):
change_name(os.path.join(path, x)) #os.path.join()在路径处理上很有用
img_dir = '\\home\\homer\\images'
print img_dir
img_dir = img_dir.replace('\\','/')
print img_dir
start = time.time()
i = 0
change_name(img_dir)
c = time.time() - start
print('程序运行耗时:%12.10f'%(c))
print('总共处理了 %s 张图片'%(i))
运行结果:
\home\homer\images
/home/homer/images
('/home/homer/images', '4.png')
old = /home/homer/images/4.png
new = /home/homer/images/4.png
('/home/homer/images', '5.jpg')
old = /home/homer/images/5.jpg
new = /home/homer/images/5.jpg
('/home/homer/images', '3.jpg')
old = /home/homer/images/3.jpg
new = /home/homer/images/3.jpg
('/home/homer/images', '6.png')
old = /home/homer/images/6.png
new = /home/homer/images/6.png
('/home/homer/images', '1.jpg')
old = /home/homer/images/1.jpg
new = /home/homer/images/1.jpg
('/home/homer/images', '2.jpg')
old = /home/homer/images/2.jpg
new = /home/homer/images/2.jpg
程序运行耗时:0.0006089211
总共处理了 6 张图片