Home > Backend Development > Python Tutorial > How to create a file in python

How to create a file in python

藏色散人
Release: 2019-07-05 11:26:26
Original
19783 people have browsed it

How to create a file in python

How to create a file in python:

First, create a new folder named a on the computer desktop .

And remember the absolute path in this folder, this is:

C:\Users\Administrator\Desktop\a
Copy after login

Note that folder a is empty at this time.

Then open the python compiler;

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

Write at the beginning:

#!/usr/bin/python
Copy after login

This is like an opening sentence.

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

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

Use python to create a b.txt document in folder a:

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.

Write text inside:

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

Among them, \n is the newline character.

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.

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

How to create a file in python

Notes

The saving path of this document, if necessary, the absolute path, C:/Users/Administrator/Desktop/a; and, the slant inside The bar is "/", not "\". Remember.

Related recommendations: "Python Tutorial"

The above is the detailed content of How to create a file in python. 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