python文件操作

本文介绍了Python的os模块,用于文件和目录的操作,包括打开和写入文件、获取当前工作目录、处理文件路径、检查路径属性、列出目录内容以及递归遍历文件夹。同时,展示了如何处理异常情况和使用dbm创建简单的数据库。
摘要由CSDN通过智能技术生成

four = open('output.txt','w')
line1 = "This here's the wa2ttle,\n"
four.write(line1)
# four.close() 用完要记得close

x = 52
four.write(str(x))

camels = 42
print('%d' % camels)


import os

cwd = os.getcwd() # current working directory
print(cwd)

""""绝对路径"""
print(os.path.abspath('memo.txt'))

"""检查路径是否存在"""
print(os.path.exists('memo.txt'))

"""检查对象是不是一个目录"""
print(os.path.isdir('memo.txt'))
print(os.path.isdir('D:/'))

"""检查对象是不是一个文件"""
print(os.path.isfile('output.txt'))


"""返回目录内的文件列表"""
lstf = os.listdir(cwd)
print(lstf)


def walk(dirname):
    """递归遍历文件夹中的文件,即如果有子文件夹,继续遍历"""
    for name in os.listdir(dirname):
        path = os.path.join(dirname,name)
        if os.path.isfile(path):
            print(path)
        else:
            walk(path)

""""
os.path.join 接收一个目录和一个文件名做参数, 然后把它们拼接成一个完整的路径
"""




 


try:
    fin = open('bad_file')
except:
    print('Something went wrong.')

"""数据库"""
import dbm
db = dbm.open('captions','c')

db['cleese.png'] = 'Photo of John Cleese.'

print(db['cleese.png'])

"""新值替换旧值"""
db['cleese.png'] = 'Photo of John Cleese doing a silly walk'

for key in db:
    print(key,db[key])

db.close()






 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值