Home > Backend Development > Python Tutorial > Introduction to Python files and streams related knowledge

Introduction to Python files and streams related knowledge

巴扎黑
Release: 2017-09-13 09:51:53
Original
1354 people have browsed it

The following editor will bring you an article on Python files and streams (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look

1. File writing


#打开文件,路径不对会报错
f = open(r"C:\Users\jm\Desktop\pyfile.txt","w")
f.write("Hello,world!\n")
f.close()
Copy after login

2. File reading


##

#读取
f = open(r"C:\Users\jm\Desktop\pyfile.txt","r")
print(f.read())
f.close()

输出:
Hello,world!
Copy after login

3. Reading and writing lines

readline([size]) Read the entire line, including the "\n" character.

readlines([sizehint]) reads all lines and returns a list. If sizeint>0 is given, lines whose total sum is approximately sizeint bytes are returned. The actual read value may be larger than sizhint because padding is required. buffer.

writelines(sequence) Writes a sequence string list to the file. If newlines are needed, you must add newline characters to each line yourself.

4. File objects are iterable and they can be used directly in for loops.

The above is the detailed content of Introduction to Python files and streams related knowledge. 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