文件的读写(Python)
文件的读写
1. 文件的路径
在计算机中文件的路径分为相对路径和绝对路径
相对路径:当前工作目录下的文件
当前工作目录就是"py_project",文件1st.py的相对路径就是"1st.py"
绝对路径:根目录到文件的完整路径
文件2nd.py的绝对路径就是"D:\temp\py_project\2nd.py"
2. 打开和关闭文件
filehandle = open ("hello.txt", 'r') # 以读的方式打开文件hello.txt,并返回文件句柄给变量filehandle
readbuf = filehandle.read () # 读取文件hello.txt
filehandle.close () # 关闭文件句柄
print (readbuf) # 打印读取内容
3. 文件的读写操作
文件的写操作
filehandle = open ("w_test.txt", 'w')
filehandle.write ("Welcone to China!")
filehandle.close ()
文件的读操作
filehandle = open ("D:\\temp\\py_project\\w_test.txt", 'r')
read_buffer = filehandle.read ()
filehandle.close ()
print (read_buffer)
4. 文件的组合读写操作
with open ("D:\\temp\\py_project\\w_test.txt", 'r') as f:
read_buffer = f.read ()
print (read_buffer)