python中处理文件的包_Python中的文件处理

python中处理文件的包

Python文件处理 (Python file handling)

File handling is very important and error-prone in any web application. It is quite easy to have a resource leakage with files if the file reading or writing is not gracefully closed.

文件处理在任何Web应用程序中都非常重要且容易出错。 如果文件的读取或写入未正常关闭,则很容易导致文件资源泄漏。

In python, the concept of file handling is rather easy and short. The file operation takes place in below-mentioned order:

在python中, 文件处理的概念非常简单而简短。 文件操作按以下顺序进行:

  1. Open a file if a predefined or an optional mode

    如果是预定义或可选模式,则打开文件

  2. Read or write

    读或写

  3. Close the file

    关闭档案

开启档案 (Open a file)

The open() function in python, opens a file in read, write or append mode. The open() will return a file object.

python中open()函数以读取,写入或追加模式打开文件。 open()将返回一个文件对象。

Syntax:

句法:

    open(filename, mode)

There are various types of mode,

模式种类繁多,

ModeDescription
'r'Open for reading ( default mode)
'w'Open for writing
'a'Open for appending
'r+'Open for both read and write
't'Open the file in text mode
'b'Open the file in binary mode
模式 描述
'r' 打开阅读(默认模式)
'w' 开放写作
'一个' 打开追加
'r +' 打开以进行读写
't' 以文本模式打开文件
'b' 以二进制模式打开文件

读取文件 (Reading a file)

# importing the module
import os

# function to read file content
def read_file(file_loc):
    file_obj = open(file_loc)
    print(file_obj.read())

# main function/code
if __name__ == '__main__':
    dir_name = os.path.dirname(__file__)
    file_name = os.path.join(dir_name, 'samples/sample_file.txt')
    read_file(file_name)

Output

输出量

this is a sample file

In the above example, if the mode is not passed as an argument, then the file is opened with "read" mode.

在上面的示例中,如果未将模式作为参数传递,则使用“读取”模式打开文件。

Another way to read a file is to invoke only required number of characters.

读取文件的另一种方法是仅调用所需数量的字符。

# importing the module
import os

# function to read file content
def read_file(file_loc):
    file_obj = open(file_loc)
    print(file_obj.read(10))

# main function/code
if __name__ == '__main__':
    dir_name = os.path.dirname(__file__)
    file_name = os.path.join(dir_name, 'samples/sample_file.txt')
    read_file(file_name)

Output

输出量

this is a

To read the lines of the file as a list, use the function readlines(), returns a list of lines in the entire file. The reading methods return empty values when the EOF is reached.

要将文件的行作为列表读取,请使用函数readlines() ,返回整个文件中的行的列表。 达到EOF时,读取方法将返回空值。

# importing the module
import os

# function to read file content
def read_file(file_loc):
    file_obj = open(file_loc)
    print(file_obj.readlines())

# main function/code
if __name__ == '__main__':
    dir_name = os.path.dirname(__file__)
    file_name = os.path.join(dir_name, 'samples/sample_file.txt')
    read_file(file_name)

Output

输出量

['this is a sample file']

写入文件 (Writing to a file)

# importing the module
import os

# function to read file content
def read_file(file_loc):
    file_obj = open(file_loc)
    print(file_obj.read())
    #print(file_obj.read(10))

# function to write to the file
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()

# main function/code
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)

In the above example, we see the method close(), it is very important that the file object which is opened to write is always closed in order to terminate the resources in use and frees the system.

在上面的示例中,我们看到了close()方法,非常重要的一点是,要写入的文件对象始终处于关闭状态,以终止使用中的资源并释放系统。

追加模式 (Append Mode)

# importing the module
import os

# function to read file content
def read_file(file_loc):
    file_obj = open(file_loc)
    print(file_obj.read())

# function to write to the file
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()

# appending the file
def append_file(file_loc):
    file_obj = open(file_loc, "a")
    file_obj.write("\n appending the information")
    file_obj.close()
    

# main function/code
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)

Output

输出量

MY sample file for include_help
I can write long long lines
 appending the information

The append mode is used in case of appending the file with additional information, and not to create the file at every invocation.

附加模式用于在文件中附加其他信息,而不是在每次调用时都创建文件。

with()方法 (with() method)

with() method is a useful method which closes all the file opened in any mode, automatically and also done the auto cleanup.

with()方法是一种有用的方法,它可以自动关闭以任何方式打开的所有文件,并完成自动清理。

# importing the module
import os

# function for read operation
def with_read_operation(file_loc):
    with open(file_loc) as file_obj:
        data = file_obj.read()
    print(data)

# function for write operation
def with_write_operation(file_loc):
    with open(file_loc, "w") as file_obj:
        file_obj.write("writing using with()")

# main function/code
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)

Output

输出量

writing using with()

Other file operations are

其他文件操作是

MethodDescription
tell()Returns an integer giving the file objects current position in the file represented as number of bytes from the beginning of the file.
seek(offset, whence)Changes the file object position. The position is computed from adding the offset to a ref point, and the ref point is selected from the whence argument.
方法 描述
告诉() 返回一个整数,给出文件对象在文件中的当前位置,表示为从文件开头开始的字节数。
搜寻(偏移量,位置) 更改文件对象的位置。 通过将偏移量与参考点相加来计算位置,并从whence参数中选择参考点。

翻译自: https://www.includehelp.com/python/file-handling.aspx

python中处理文件的包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值