python中用write逐行写入txt文件
时间: 2023-10-02 15:10:14 浏览: 59
在Python中,使用以下代码逐行写入txt文件:
```
with open("filename.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
```
这段代码会创建一个名为"filename.txt"的文件,然后逐行写入"Line 1","Line 2"和"Line 3",每行末尾添加换行符"\n"。要追加内容到现有文件中而不是覆盖现有内容,使用选项"a"代替"w"。例如:
```
with open("filename.txt", "a") as file:
file.write("Line 4\n")
```
这段代码将在现有文件的末尾添加一行"Line 4"。
相关问题
在python中用string函数写入txt文本文件,I love python字符串
以下是使用Python的示例代码:
```python
str = "I love python"
with open("output.txt", "w") as outfile:
outfile.write(str)
print("写入成功!")
```
这段代码使用`with open()`语句打开一个名为"output.txt"的文件,使用"w"模式表示写入模式。然后使用`write()`方法将字符串写入文件中,最后`with`语句块结束时会自动关闭文件。如果文件打开失败,则会抛出异常。如果写入成功,则输出写入成功的信息。
python中用with open写入文件的实例代码
下面是一个使用`with open`向文件中写入内容的示例代码:
```python
with open('example.txt', 'w') as f:
f.write('Hello, world!')
```
在上面的代码中,我们打开一个名为`example.txt`的文件,使用`with open`语句来确保文件在使用完毕后被正确关闭。`'w'`表示以写入模式打开该文件。使用`f.write()`方法向文件中写入`'Hello, world!'`字符串。当`with`块结束时,文件将被自动关闭并保存。