在任何Web应用程序中,文件处理都非常重要并且容易出错。如果文件的读取或写入未正常关闭,则很容易发生文件资源泄漏。
在python中,文件处理的概念非常简单且简短。文件操作按以下顺序进行:
如果是预定义或可选模式,则打开文件
读或写
关闭档案
open()python中的函数,以读取,写入或追加模式打开文件。该open()会返回一个文件对象。
语法:
open(filename, mode)
模式有很多种,
| 模式 | 描述 |
|---|---|
| 'r' | 打开阅读(默认模式) |
| 'w' | 开放写作 |
| '一种' | 打开追加 |
| 'r +' | 打开以进行读写 |
| 't' | 以文本模式打开文件 |
| 'b' | 以二进制模式打开文件 |
# 导入模块 import os # 读取文件内容的功能 def read_file(file_loc): file_obj = open(file_loc) print(file_obj.read()) # 主要功能/代码 if __name__ == '__main__': dir_name = os.path.dirname(__file__) file_name = os.path.join(dir_name, 'samples/sample_file.txt') read_file(file_name)
输出结果
this is a sample file
在上面的示例中,如果未将模式作为参数传递,则使用“读取”模式打开文件。
读取文件的另一种方法是仅调用所需数量的字符。
# 导入模块 import os # 读取文件内容的功能 def read_file(file_loc): file_obj = open(file_loc) print(file_obj.read(10)) # 主要功能/代码 if __name__ == '__main__': dir_name = os.path.dirname(__file__) file_name = os.path.join(dir_name, 'samples/sample_file.txt') read_file(file_name)
输出结果
this is a
要将文件的行作为列表读取,请使用函数readlines(),返回整个文件中的行列表。达到EOF时,读取方法将返回空值。
# 导入模块 import os # 读取文件内容的功能 def read_file(file_loc): file_obj = open(file_loc) print(file_obj.readlines()) # 主要功能/代码 if __name__ == '__main__': dir_name = os.path.dirname(__file__) file_name = os.path.join(dir_name, 'samples/sample_file.txt') read_file(file_name)
输出结果
['this is a sample file']
# 导入模块
import os
# 读取文件内容的功能
def read_file(file_loc):
file_obj = open(file_loc)
print(file_obj.read())
#print(file_obj.read(10))
# 写入文件的功能
def write_file(file_loc):
file_obj = open(file_loc, "w")
file_obj.write("MY sample file for include_help\n")
file_obj.write("I can write long long lines")
file_obj.close()
# 主要功能/代码
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
write_file_name = os.path.join(dir_name, 'samples/sample_file_1.txt')
write_file(write_file_name)
read_file(write_file_name)在上面的示例中,我们看到了方法close(),非常重要的一点是,要写入的文件对象始终处于关闭状态,以终止使用中的资源并释放系统。
# 导入模块
import os
# 读取文件内容的功能
def read_file(file_loc):
file_obj = open(file_loc)
print(file_obj.read())
# 写入文件的功能
def write_file(file_loc):
file_obj = open(file_loc, "w")
file_obj.write("MY sample file for include_help\n")
file_obj.write("I can write long long lines")
file_obj.close()
# 附加文件
def append_file(file_loc):
file_obj = open(file_loc, "a")
file_obj.write("\n appending the information")
file_obj.close()
# 主要功能/代码
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
write_file_name = os.path.join(dir_name, 'samples/sample_file_1.txt')
write_file(write_file_name)
append_file(write_file_name)
read_file(write_file_name)输出结果
MY sample file for include_help I can write long long lines appending the information
附加模式用于在文件中附加其他信息的情况,而不是在每次调用时都创建文件。
with()method是一种有用的方法,它会自动关闭以任何方式打开的所有文件,并完成自动清理。
# 导入模块
import os
# 读取操作功能
def with_read_operation(file_loc):
with open(file_loc) as file_obj:
data = file_obj.read()
print(data)
# 写入操作功能
def with_write_operation(file_loc):
with open(file_loc, "w") as file_obj:
file_obj.write("writing using with()")
# 主要功能/代码
if __name__ == '__main__':
dir_name = os.path.dirname(__file__)
write_file_name = os.path.join(dir_name, 'samples/sample_file_2.txt')
with_write_operation(write_file_name)
with_read_operation(write_file_name)输出结果
writing using with()
其他文件操作是
| 方法 | 描述 |
|---|---|
| tell() | 返回一个整数,给出文件对象在文件中的当前位置,表示为从文件开头开始的字节数。 |
| seek(offset, whence) | 更改文件对象的位置。通过将偏移量与参考点相加来计算位置,并从whence参数中选择参考点。 |