How to create txt file in python and write it

coldplay.xixi
Release: 2023-01-03 09:29:03
Original
84001 people have browsed it

How to create and write a txt file in python: first start writing [#!/usr/bin/python] and set the encoding format; then create a txt document and write text in it; finally open the document That’s it.

How to create txt file in python and write it

The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.

How to create and write txt files in python:

1. Open the python compiler;

The python I use is integrated with Anaconda The compiler corresponding to the python3 version: spyder.

How to create txt file in python and write it

2. Write at the beginning:

#!/usr/bin/python
Copy after login

This is like an opening statement.

How to create txt file in python and write it

3. Since you need to output Chinese, you need to set the encoding format:

# -*- coding:utf-8 -*-
Copy after login

How to create txt file in python and write it

4. Use python In folder a, create a b.txt document:

file = open('C:/Users/Administrator/Desktop/a/b.txt','w')
Copy after login

'w' means that this document can be edited, which means it can be read and written.

How to create txt file in python and write it

5. Write text inside:

file.write('你好,\n  世界。')
Copy after login

Among them, \n is the newline character.

How to create txt file in python and write it

6. The overall code is as follows:

#!/usr/bin/python
# -*- coding:utf-8 -*-
file = open('C:/Users/Administrator/Desktop/a/b.txt','w')
file.write('你好,\n  世界。')
Copy after login

At this time, there is already a b.txt document in the a folder.

How to create txt file in python and write it

7. Open this document and you can see the content as shown below.

How to create txt file in python and write it

Related free learning recommendations: python video tutorial

The above is the detailed content of How to create txt file in python and write it. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template