Python 简明教程
Python - Write to File
对文件进行写入涉及以特定模式打开文件、向其写入数据,然后关闭文件以确保保存所有数据并释放资源。 Python 提供了一个内置函数 open() 来处理文件操作和各种写入数据的方法。
Writing to a file involves opening the file in a specific mode, writing data to it, and then closing the file to ensure that all data is saved and resources are released. Python provides a built-in function open() to handle file operations and various methods for writing data.
Opening a File for Writing
打开文件进行写入是执行 Python 中写入操作的第一步。open() 函数用于以不同模式打开文件,每种模式都适用于特定用例。
Opening a file for writing is the first step in performing write operations in Python. The open() function is used to open files in different modes, each suited for specific use cases.
The open() Function
open() 函数在 Python 中用于打开文件。它至少需要一个参数(文件名),可以接受一个可选的第二个参数,该参数指定应打开文件的模式。
The open() function in Python is used to open a file. It requires at least one argument, the name of the file, and can take an optional second argument that specifies the mode in which the file should be opened.
File Modes for Writing
以下是用于将文件打开为写入模式的主要模式 −
Following are the main modes you can use to open a file for writing −
-
w (Write mode) − Opens the file for writing. If the file exists, it truncates (empties) the file before writing. If the file does not exist, it creates a new file.
-
a (Append Mode) − Data is written at the end of the file. If the file does not exist, it creates a new file.
-
x (Exclusive Creation Mode) − Opens the file for exclusive creation. If the file already exists, the operation fails.
-
b (Binary Mode) − When used with other modes, opens the file in binary mode.
-
+ (Update Mode) − Opens the file for updating (reading and writing).
当你想从头开始,每次打开该文件时,往该文件里写入数据时,使用该模式 −
This mode is used when you want to write data to a file, starting from scratch each time the file is opened −
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
print ("File opened successfully!!")
以下是所获得的输出 −
Following is the output obtained −
File opened successfully!!
当你想将数据添加到该文件末尾时,而不用改变其现有内容时,使用该模式 −
This mode is used when you want to add data to the end of the file without altering its existing contents −
file = open("example.txt", "a")
file.write("Appending this line.\n")
file.close()
print ("File opened successfully!!")
这会产生以下结果 −
This will produce the following result −
File opened successfully!!
Writing to a File Using write() Method
write() 方法用来将一个字符串写入文件。这使其适用于各种基于文本的文件操作。
The write() method is used to write a single string to a file. This makes it suitable for various text-based file operations.
write() 方法采取单个参数:你想写入文件的字符串。它将该字符串的确切内容写入文件,而无需添加任何附加字符,例如换行符。
The write() method takes a single argument: the string that you want to write to the file. It writes the exact content of the string to the file without adding any additional characters, such as newlines.
Example
在下面的示例中,我们以写入模式打开文件“example.txt”。然后我们使用 write() 方法将一个字符串写入文件 −
In the following example, we are opening the file "example.txt" in write mode. We then use the write() method to write a string to the file −
# Open a file in write mode
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line.\n")
print ("File opened successfully!!")
以下是上面代码的输出: -
Following is the output of the above code −
File opened successfully!!
Writing to a File Using writelines() Method
writelines() 方法用来将一个字符串列表写入文件。列表中的每一个字符串都被顺序写入文件,无需自动添加任何换行符。
The writelines() method is used to write a list of strings to a file. Each string in the list is written to the file sequentially without adding any newline characters automatically.
Example
在这个示例中,我们创建一个字符串列表 lines,列表中的每个字符串都以换行符结尾。然后我们以写入模式打开文件“example.txt”,并使用 writelines() 方法将列表中的所有字符串一次性写入文件 −
In this example, we are creating a list of strings, lines, with each string ending in a newline character. We then open a file "example.txt" in write mode and use the writelines() method to write all the strings in the list to the file in one operation −
# List of lines to write to the file
lines = ["First line\n", "Second line\n", "Third line\n"]
# Open a file in write mode
with open("example.txt", "w") as file:
file.writelines(lines)
print ("File opened successfully!!")
获得的输出如下所示 −
The output obtained is as shown below −
File opened successfully!!
Writing to a New File
在 Python 中写入新文件需要创建一个新文件(或覆盖现有的文件)并向其中写入所需内容。在此,我们将解释写入新文件的步骤 −
Writing to a new file in Python involves creating a new file (or overwriting an existing one) and writing the desired content to it. Here, we will explain the steps involved in writing to a new file −
-
Open the File − Use the open() function to create or open a file in write mode ("w" or "wb" for binary files).
-
Write Data − Use the write() or writelines() method to write data to the file.
-
Close the File − Ensure the file is properly closed after writing, generally using the "with" statement for automatic handling.
Example
在下面的示例中,我们创建一个“foo.txt”文件,并向该文件中写入给定内容,最后关闭该文件 −
In the example below, we create a "foo.txt" file and write given content in that file and finally close that file −
# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
# Close opened file
fo.close()
如果你使用任何文本编辑应用程序(如记事本)打开此文件,它将具有以下内容 −
If you open this file with any text editor application such as Notepad, it will have the following content −
Python is a great language.
Yeah its great!!
Writing to a New File in Binary Mode
默认情况下,文件对象上的读/写操作在文本字符串数据上执行。如果我们需要处理不同类型文件,比如媒体文件(mp3)、可执行文件(exe)或图片(jpg),我们必须通过将 'b' 前缀添加到读/写模式中,以二进制模式打开文件。
By default, read/write operations on a file object are performed on text string data. If we need to handle files of different types, such as media files (mp3), executables (exe), or pictures (jpg), we must open the file in binary mode by adding the 'b' prefix to the read/write mode.
Writing Binary Data to a File
要将二进制数据写入文件,在二进制写模式('wb')中打开文件。以下示例演示此操作 −
To write binary data to a file, open the file in binary write mode ('wb'). The following example demonstrates this −
# Open a file in binary write mode
with open('test.bin', 'wb') as f:
# Binary data
data = b"Hello World"
f.write(data)
Converting Text Strings to Bytes
文本字符串到字节的转换可以使用 encode() 函数完成。当您需要将文本数据作为二进制数据写入时,此操作非常有用 −
Conversion of a text string to bytes can be done using the encode() function. This is useful when you need to write text data as binary data −
# Open a file in binary write mode
with open('test.bin', 'wb') as f:
# Convert text string to bytes
data = "Hello World".encode('utf-8')
f.write(data)
Writing to an Existing File
当以写模式('w')打开现有文件时,其以前的内容会被清除。以写权限打开文件会将其视为新文件。要将数据添加到现有文件中而不清除其内容,您应该以追加模式('a')打开文件。
When an existing file is opened in write mode ('w'), its previous contents are erased. Opening a file with write permission treats it as a new file. To add data to an existing file without erasing its contents, you should open the file in append mode ('a').
Example
以下示例演示如何以追加模式打开文件并在其中添加新文本 −
The following example demonstrates how to open a file in append mode and add new text to it −
# Open a file in append mode
fo = open("foo.txt", "a")
text = "TutorialsPoint has a fabulous Python tutorial"
fo.write(text)
# Close opened file
fo.close()
如果你使用任何文本编辑应用程序(如记事本)打开此文件,它将具有以下内容 −
If you open this file with any text editor application such as Notepad, it will have the following content −
Python is a great language.
Yeah its great!!
TutorialsPoint has a fabulous Python tutorial
Writing to a File in Reading and Writing Modes
当使用 'w' 或 'a' 打开文件进行写入时,无法在文件中的任何早期字节位置执行写操作。然而,'w+' 模式可以在不关闭文件的情况下执行读写操作。seek() 函数用于将读/写指针移动到文件中的任何所需字节位置。
When a file is opened for writing using 'w' or 'a', it is not possible to perform write operations at any earlier byte position in the file. The 'w+' mode, however, allows both reading and writing operations without closing the file. The seek() function is used to move the read/write pointer to any desired byte position within the file.
Using the seek() Method
seek() 方法用于设置文件内读/写指针的位置。seek() 方法的语法如下 −
The seek() method is used to set the position of the read/write pointer within the file. The syntax for the seek() method is as follows −
fileObject.seek(offset[, whence])
其中,
Where,
-
offset − This is the position of the read/write pointer within the file.
-
whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file’s end.
以下程序演示如何以读写模式('w+')打开文件,写入一些数据,查找特定位置,然后覆盖文件内容的一部分 −
The following program demonstrates how to open a file in read-write mode ('w+'), write some data, seek a specific position, and then overwrite part of the file’s content −
# Open a file in read-write mode
fo = open("foo.txt", "w+")
# Write initial data to the file
fo.write("This is a rat race")
# Move the read/write pointer to the 10th byte
fo.seek(10, 0)
# Read 3 bytes from the current position
data = fo.read(3)
# Move the read/write pointer back to the 10th byte
fo.seek(10, 0)
# Overwrite the existing content with new text
fo.write('cat')
# Close the file
fo.close()
如果我们在读取模式下打开文件(或在 'w+' 模式下找到起始位置)并读取内容,它将显示以下内容 −
If we open the file in read mode (or seek to the starting position while in 'w+' mode) and read the contents, it will show the following −
This is a cat race