Python files open and close

open a file

1. Establish a program object file on disk with associated
2. Access to relevant documents by subject

File Operations

(1) read (2) writing (3) Other: adding, computing

Close the file

(1) cut off contact with the program file
(2) written to disk, and releases file buffers

open a file

Open( )
<variable> = open (<name>, <mode>)<name>磁盘文件名
<mode>打开模式

Open mode
Here Insert Picture Description
Here Insert Picture Description

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
 #例如,打开一个名为7.1.txt文件
 textfile = open("7.1.txt",'r')
 
 #打开一个music.mp3的音频文件
 binfile = open('music.mp3','rb')

After use close the file using () method to close, release the license file format:

<Variable name> .close ()

Read and write files

  • read () Returns a string that contains the value of the contents of the entire file

  • the readline () Returns the value of the contents of the file string of the next line.

  • readlines () Returns the value of the entire contents of the file list, each newline to the end of his string.

#1
fname =  input("输入你要打开的文件:")
fo = open(fname,'r')
for line in fo.readlines():
print(line)
fo.close()
#2
with open ("demo1.txt",'r',encoding='utf8')as f:
for line in f.readlines():
print(line,end='')

The code applies only to short code, the disadvantage is: when the file is very large, one-time to read the contents of the list will take up a lot of memory,

Rigid enforcement of speed. Reasonable approach is progressive read into memory, and progressive process. Python file itself as a sequence of rows,

All lines traverse the document.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
fname =  input("输入你要打开的文件:")
fo = open(fname,'r')
for line in fo():
print(line)
fo.close()

Write to file

Data is written to the file from the computer's memory

  • write (): This article contains a string or binary data blocks written to the file.
  • writelines (): For a list of actions to receive a list of strings as arguments, it
    had written to the file.
#写法一
fname = input("请输入要写入的文件:")
fo = open(fname,'w+')
lst = ['This is a demo ','and demo']
fo.writelines(lst)
for line in fo:
print(line)
fo.close()

#写法二
lst=['This is a demo ','and demo']
with open ("demo1.txt",'a',encoding='utf8')as f:
    for x in lst:
        f.write('{}\n'.format(x))
        
with open ("demo1.txt",'r',encoding='utf8')as f:
    for line in f.readlines():
        print(line,end='')

Results of the:

Here Insert Picture Description

Published 705 original articles · won praise 833 · Views 1.36 million +

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/105202071