如何在Python中将字符串写入文件?


要在Python中将字符串写入文件,您可以按照以下步骤操作:

使用`open()`函数以写入模式打开文件,并将其赋值给一个变量。

在文件变量上调用`write()`函数,并将要写入的文件的字符串作为参数传递。这会将字符串写入文件。

使用`close()`函数关闭文件,以确保文件已正确保存。

以下是一个演示如何在文件中写入字符串的代码片段:

以写入模式打开文件

示例

在下面的代码中,我们以写入模式创建一个名为“example.txt”的文件。然后,我们使用`write()`函数将字符串写入此文件。最后,我们使用`close()`函数关闭文件。

file = open("example.txt", "w")
# Write string to file
file.write("This is an example string to be wrapped in a file.")
# Close the file
file.close()

输出

如果在运行上述代码后打开example.txt文件,它将显示以下内容:“This is an example string to be wrapped in a file.”

使用`with`语句将字符串写入文件

您还可以使用`with`语句将字符串写入文件,该语句会在代码块结束后自动关闭文件。这是一个示例:

示例

在此代码中,我们使用`with`语句打开文件并将字符串写入其中。代码块结束后,文件将自动关闭。

with open("example.txt", "w") as file:
    file.write("This is an example string to be wrapped in a file.")

输出

如果在运行上述代码后打开example.txt文件,它将显示以下内容:“This is an example string to be wrapped in a file.”

将字符串追加到现有文件

您还可以使用`a`(追加)模式而不是`w`(写入)模式将字符串追加到现有文件。这是一个示例:

示例

在此代码中,我们使用‘a’标志以追加模式打开包含内容“This is a demo text file”的现有文本文件“example2.txt”。然后,我们将新的一行和追加的字符串写入文件。

with open("example2.txt", "a") as file:
    file.write("\nThis is an appended string.")

输出

在运行上述代码后打开example2.txt文本文件时,它将显示以下内容:“This is a demo text file

This is an appended string.”

以下是三个更具体的代码示例,逐步说明如何在Python中将字符串写入文件:

使用`with`语句和`write()`方法

示例

此代码使用`with`语句创建一个名为output.txt的新文件并以写入模式打开它。然后,它使用`write()`方法将字符串“Hello, World!”写入文件。`with`语句在代码块退出时自动关闭文件,确保文件已正确保存。

# Open the file in write mode
with open('output.txt', 'w') as f:
    # Write the string to the file
    f.write('Hello, World!')

输出

如果在运行上述代码后打开output.txt文件,它将显示以下内容:“Hello, World!”

使用`open()`函数和`write()`方法

示例

此代码类似于前面的示例,但它使用`open()`函数创建一个文件对象,并使用`close()`方法关闭文件。虽然此方法有效,但通常最好使用`with`语句来确保文件已正确关闭。

# Open the file in write mode
f = open('output2.txt', 'w')
# Write the string to the file
f.write('Hello, World!')
# Close the file
f.close()

输出

如果在运行上述代码后打开output2.txt文件,它将显示以下内容:“Hello, World!”

使用`print()`函数和`file`参数

示例

此代码使用`print()`函数将字符串“Hello, World!”写入文件。`file`参数用于指定输出应定向到的文件对象。此方法还需要使用`close()`方法手动关闭文件。

# Open the file in write mode
f = open('output3.txt', 'w')
# Use the print function to write the string to the file
print('Hello, World!', file=f)
# Close the file
f.close()

输出

如果在运行上述代码后打开output3.txt文件,它将显示以下内容:“Hello, World!”

示例

在这个例子中,我们首先使用`open()`函数以写入模式创建一个名为'myfile.txt'的新文件,并使用`write()`方法将字符串'This is my string'写入其中。然后我们使用`with`语句关闭文件。接下来,我们再次使用`open()`函数以读取模式打开文件,并使用`read()`方法读取文件的内容。最后,我们打印文件的内容。

# create a file and write a string to it
with open('myfile.txt', 'w') as f:
    f.write('This is my string')
# read the file and print its contents
with open('myfile.txt', 'r') as f:
    contents = f.read()
    print(contents)

输出

如果运行上述代码,它将打印“This is my string”到控制台。

更新于:2023年8月10日

2K+ 浏览量

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.