Python文件处理操作

In this tutorial, we will learn how to read content from a file, then write text to any file and how to copy a file content to another file. We will also use tell and seek methods for file handling.

在本教程中,我们将学习如何从文件读取内容,然后将文本写入任何文件以及如何将文件内容复制到另一个文件。 我们还将使用tell and seek方法进行文件处理。

Python-读取文件 (Python - Reading a File)

Let's start by learning how to read a file.

让我们从学习如何读取文件开始。

readline() function is used to read a line in the document. It can be used like:

readline()函数用于读取文档中的一行。 可以像这样使用:

>>> myFile.readline()

where myFile is the instance of the file. readline() function will simply print the whole line starting from the cursor's position.

其中, myFile是文件的实例。 readline()函数将简单地从光标的位置开始打印整行。

In order to print the whole content of the file, iterating line by line, we can use a for loop:

为了打印文件的全部内容,逐行迭代,我们可以使用for循环:

for line in myFile:
    # will print all the lines one by one
    print (line)

Beside using iteration, there is another way of reading the whole file, using readlines() function(notice it is readlines, which is different from readline). Using the function will return a list that will contain each line of the file. Because of this, one should be careful while using this function. In case there is lots of data in the file, the list may take lots of space, and thus making the whole reading time longer. Thus, it is recommended to use this function only for reading shorter files which can be stored in a list efficiently.

除了使用迭代之外,还有一种使用readlines()函数读取整个文件的方法(请注意,这是readlines,这与readline不同)。 使用该函数将返回一个包含文件每一行的列表。 因此,使用此功能时应格外小心。 如果文件中有很多数据,则列表可能会占用很多空间,从而使整个读取时间更长。 因此,建议仅将此功能用于读取可以有效存储在列表中的较短文件。

It is used pretty much like readlines() only, except that in this case we need to store the returned value in some variable:

它的用法非常像readlines() ,除了在这种情况下,我们需要将返回值存储在某个变量中:

>>> content = myFile.readlines()

Similar thing can done manually using iterative approach:

类似的事情可以使用迭代方法手动完成:

content = []
for line in myFile:
    content.append(line)

This will iteratively append each line of the file on content list.

这将迭代地将文件的每一行追加到内容列表中。

Python-写入文件 (Python - Writing to a file)

write() function is used to write a single string into the file. For example, there is a string

write()函数用于将单个字符串写入文件。 例如,有一个字符串

>>> content = "Hello, World. I am learning Python."
# In order to write this line in a file
>>> myFile.write(content)

or

要么

>>> myFile.write("Hello, World. I am learning Python")

Write can't be used for writing the content of list or tuple. In such cases, writelines() function is used.

写不能用于写列表或元组的内容。 在这种情况下,将使用writelines()函数。

>>> content = ["Python 3.x\n", "Hello, World. I am learning Python"]
>>> myFile.writelines(content)

Executing this will write the file content with:

执行此操作将使用以下命令写入文件内容:

Python 3.x
Hello, World. I am learning Python

Python-讲述与寻求 (Python - Tell and Seek)

As we mentioned before once you open a file there is a cursor that keeps moving once as you read or write. It's sometimes important to move this cursor around without making any variable read or write every time, and for this purpose, there is a seek() function available to move to the desired location within a file.

正如我们之前提到的,一旦打开文件,在读取或写入时,光标就会一直移动一次。 有时在不每次进行任何变量读写的情况下移动此光标非常重要,因此,有一个seek()函数可用于移动到文件中的所需位置。

>>> myFile.seek(offset, [start_from])

offset decides how many bytes you want to skip, here second argument start_from is optional, which decides from which place you want to start. Possible values can be-

offset决定要跳过多少个字节,这里第二个参数start_from是可选的,它决定要从哪个位置开始。 可能的值可以是-

  • 0 - Beginning of file

    0-文件开始

  • 1 - Current position of file

    1-文件的当前位置

  • 2 - End of file

    2-文件结束

In case the argument is not being specified, by default, it's 0. 如果未指定参数,则默认为0。

Suppose there is a file(file.txt) with content Hello, World!

假设有一个文件(file.txt),内容为Hello,World!

Then using the seek function as below:

然后使用如下的seek函数:

>>> myFile = open('file.txt','r+')
>>> myFile.seek(5)
>>> myFile.read()
', World!'

As you can see here, the seek() function skipped first 5 bytes (i.e., 'Hello' and read the next bytes till the end of the line. In order to get the current position of the pointer, tell() function can be used. It will return the byte's pointer is away from the beginning.

如您在此处看到的, seek()函数跳过了前5个字节(即“ Hello”,并读取了下一个字节,直到该行的末尾。为了获得指针的当前位置,可以使用tell()函数tell()它将返回该字节的指针远离起始位置。

>>> myFile.tell()

Python-复制文件 (Python - Copying a File)

Pick the file to copy and create its object. Create another object and use open() to create a new file(writing the path in open() function creates the file if it doesn’t exist). read() content from first file. write() the same in the other file.

选择要复制的文件并创建其对象。 创建另一个对象,然后使用open()创建一个新文件(在open()函数中写入路径将创建该文件,如果该文件不存在)。 从第一个文件中read()内容。 在另一个文件中的write()相同。

>>> file1 = open("original.txt", "r")
>>> file2 = open("duplicate.txt", "w")
>>> l = file1.readline()
>>> while l:
 		file2.write(l)
		l = file1.readline()
>>> file1.close()
>>> file2.close()

Open the file duplicate.txt and you should be able to see the copied text.

打开文件plicate.txt ,您应该能够看到复制的文本。

翻译自: https://www.studytonight.com/python/reading-and-writing-file

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值