python读写文件实例(六)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import os

def function():
    pwd = os.getcwd()
    print("当前文件的路径:", pwd)
    print("当前文件的父路径:",os.path.abspath(os.path.dirname(pwd) + os.path.sep + "."))
    print("当前文件的前两级目录:", os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".."))

    print("当前位置所在的文件名:",sys._getframe().f_code.co_filename)
    print("当前位置所在的函数名:",sys._getframe().f_code.co_name)
    print("当前位置所在的行号:",sys._getframe().f_lineno)
function();

#读取取utf8文件,第一种方式
f=None
try:
    filePath=os.getcwd()+os.path.sep+"05enum.py"
    print(filePath)
    f=open(filePath,"r", encoding='utf8',errors='ignore')
    #一次性,读取全部文件内容
    fileAllContent=f.read();
    print(fileAllContent)
finally:
    if f:
        f.close()

#读取取utf8文件,第二种方式
filePath=os.getcwd()+os.path.sep+"05enum.py"
with open(filePath, 'r', encoding='utf8',errors='ignore') as f:
    # 按行,读取文件内容
    lineNo = 0
    for line in f.readlines():
        lineNo = lineNo + 1;
        print("lineNo",lineNo,":",line.strip())  # 把末尾的'\n'删掉

#写文件( r只读,w可写,a追加)
filePath=os.getcwd()+os.path.sep+"write.py"
with open(filePath,"a",encoding='utf8',errors='ignore')as f:
    f.write("ahello,world\n")
    f.write("bhello,world\n")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值