with open语法应用

'''
with open语法应用:
    通过with open,可以在文件操作结束后,自动关闭被操作的文件,无需再调用close方法关闭
    with open(file,mode,encoding) as 别名:
        文件操作代码块
    1.open调用时,与常规保持一致。
    2.操作文件时,通过别名直接调用该文件对象。
    3.一般都是操作单个文件。


'''

# with open(file='./mpf.txt', mode='r', encoding='utf-8') as file:
#     content = file.read()
#
# print(content) #with open语法中产生的内容,可以被外部直接调用


'''
    文件的路径读取机制:
        程序在执行的时候,有他们自己的文件路径启动的。
        在哪里运行程序,初始路径就在哪里
        程序在执行时,如果是相对路径调用,则需要考虑文件的初始路径。
        如果是绝对路径则不需要考虑。但是代码的移植性比较差。
        
        为了解决路径问题,所以初期推荐封装函数时将文件路径作为参数传入即可
'''


def file_read(f):
    with open(file=f, mode='r', encoding='utf-8') as file:
        content = file.read()
    return content


print(file_read('./hcc.txt'))
# print(file_read(r'D:\pyworkspace\python_class_hcc_v6\class07_file\hcc.txt'))
# print(file_read())

 

posted @ 2024-12-08 09:18  mafei666  阅读(139)  评论(0)    收藏  举报