文件读写

#! /usr/bin/python3
# -*-coding:UTF-8-*-
path = '/var/www/python/file.txt'
f_name = open(path)     #注意:如果open()不带access_mode变量时,被打开文件一定要存在,否则会报错
print("文件路径:",f_name.name)
print("打开文件模式:",f_name.mode)

#注意:
# 如果带上access_mode变量,以写入w方式打开,
# 如果该文件不存在就会创建该文件,如果已经存在该文件会被覆盖掉
# file_name = open("/var/www/python/test.txt","w")
# print(file_name)

#缓冲
# I/O,是指Input/Output,输入和输出,缓存一般是指内存,如果open()的第三个参数赋值为0或者false
# 就是无缓存,如果是1或者true,就是有缓存,-1或者小于0的整数就代表使用默认的缓存大小

# 读文件
file_content = open(path)
print("内容为:",file_content.read())

# 写入文件
write_content = open(path,'a')      # a模式是追加写入,如果文件不存在,先创建文件,再写入
content = 'this is my content .\n'
print("写入长度:",write_content.write(content))
write_content = open(path,'r')
print("写入后内容为:",write_content.read())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章