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()
2. File reading
##
#读取 f = open(r"C:\Users\jm\Desktop\pyfile.txt","r") print(f.read()) f.close() 输出: Hello,world!
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!