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

Python练习代码 -- 字符串和正则表达式, 文件文件夹操作

2014-08-08 15:14 816 查看
# -*- mode: python; coding: utf-8 -*-

############# 字符串 和 正则表达式 ###########
str1 = "version"
num = 1.0
formatx = "%s %f" %(str1,num)
print(formatx)
print(str1.center(20))
print(str1.center(20,"*")) #居中
print(str1.ljust(20))  #左对齐
print(str1.rjust(20))  #右对齐

strs = ["hello ", "world"]
result1 = "".join(strs)
print(result1[0:8])
print(result1.split(" "))

print(result1.startswith("he", 0, 5))
print(result1.endswith("ld", 6, len(result1)))
print(result1.find("h", 0, 5))
print(result1.replace("hello", "hehe"))

#反转
def reversex(s):
li = list(s)
li.reverse()
s = "".join(li)
return s
print( reversex("hello") )

#正则表达式
import re
s = "HELLO WORLD"
matchobj = re.match(r"^hello", s, re.I)
print( matchobj.string, matchobj.group(0) , matchobj.pos, matchobj.endpos )

############### 文件操作 ################
content = "hello world, xxxx\n"
f = file("hello.txt", "a+")
f.write(content)
#按行读取
while True:
line = f.readline()
if(line):
print(line[0:len(line)-1]) #去掉 \n
else:
break

#一次性读取
f.seek(0);
context = f.read()
print(context)
f.close()

#使用 os os.path模块
import os
realpath = os.path.abspath("hello.txt")
filenames = os.path.splitext(realpath)
print(filenames[0], filenames[1])  #拆分为文件名和后缀名

#if(os.path.exists("hello.txt")):
#    os.remove("hello.txt")

#使用shutil 复制文件
import shutil
shutil.copyfile("hello2.txt", "hello3.txt")
if( not os.path.exists("../hello3.txt")):
shutil.move("hello3.txt", "../")

#读取ini配置文件 config.ini
# [config1]
# user=kevin
# password=123456
# [config2]
# user=xiang
# password=654321
#####################
import ConfigParser
config = ConfigParser.ConfigParser();
config.read("config.ini")
sections = config.sections()
print(sections)
options = config.options("config1")
print(options)
items = config.items("config1")
print(items)
user = config.get("config1", "user")
print(user)
# 修改已存在的配置文件
config.set("config1", "password", "88888")
config.remove_option("config2", "password")
f = open("config.ini", "w+")
config.write(f)
f.close()

#历遍目录 os.path.walk, arg为walk传入的参数()
def VisitDir(arg, dirnames, filenames):
#print(arg, dirnames, filenames)
for name in filenames:
print( os.path.join(dirnames, name) )
os.path.walk(".", VisitDir, ())

# 使用os下的walk, 返回一个元组,3个元素,分别是路径名,目录列表,文件列表
for root, dirs, files in os.walk("."):
#print(root, dirs, files)
for name in files:
print(os.path.join(root, name))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: