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


# -*- 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))

    











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值