#!/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")
python读写文件实例(六)
最新推荐文章于 2024-07-16 11:25:46 发布