The file read and write file operations python

Reading and Writing Files

#--------读写文件----------#
#1 open()函数打开文件,默认是以读模式打开
file_obj = open('E:\python_linux\s004_string_judge.py',encoding='utf-8')
#2 文件对象方法read()读取文件内容
print(file_obj.read())
#3 文件对象方法close()关闭文件
file_obj.close()

result:

#------------字符串前缀和后缀的判别方式--------#

s = "wan quan he ni hao ya !"
#--------前缀------------#
s_pro = s.startswith('wan')
print('字符串s的前缀可以是wan:',s_pro)

#--------后缀-----------#
s_end = s.endswith('ya !')
print('字符串s的后缀可以是ya !',s_end)

#-------实例:筛选某个目录下的.py文件------------#
file_list = ['a.py', 'b.py', 'c.txt', 'd.py']
py_file = [file for file in file_list if file.endswith('.py')]
print('当前路径下的python文件:',py_file)

Open the file mode

#1 'w'写模式与文件对象的write()方法
w_file_obj = open('E:\python_linux\w_file.txt','w')
w_file_obj.write('这馒头有毒!!')
w_file_obj.close()

result
Here Insert Picture Description

#2 'x'创建模式,创建一个空文件。不可用read(),但可用write方法。若文件已存在,则报错!
x_file_obj = open('E:\\python_linux\\x_file.txt','x')
x_file_obj.write('苹果很好吃!!')
x_file_obj.close()

result
Here Insert Picture Description

Close the file handle, the handle to prevent excessive

#1 finaly方式关闭;
try:
    file_obj = open('E:\\python_linux\\x_file.txt','a',encoding='gbk')
    file_obj.write("真的酸!")
finally:
    file_obj.close()

result
Here Insert Picture Description

#2 上下文管理模式 with ....as
    with open('E:\\python_linux\\x_file.txt','r',encoding='gbk') as r_file:
        print(r_file.read())

result

苹果很好吃!!真的酸!真的酸!真的酸!
Released seven original articles · won praise 2 · views 95

Guess you like

Origin blog.csdn.net/weixin_44014460/article/details/103931920