Python basics-read and write operations

Python basics-read and write operations

1. Write operation

'''
open中在路径前面加r,r表示转义字符不转义,故不用\\
w表示覆盖写操作
'''
f=open(r"C:\out.txt","w") 
while(True):
    r=input("please enter Strings:--->")
    if(r=="exit"):
        break
    f.write(r)
f.close()

Enter aabbcc and exit and enter ddeeff
Insert picture description herefrom the result. Only ddeeff in the document knows that this write operation is overwritten
Insert picture description here

2. Write operation (append)

'''
open中在路径前面加r,r表示转义字符不转义,故不用\\
a(append())表示追加写操作
'''
f=open(r"C:\out.txt","a")
while(True):
  r=input("please enter Strings:--->")
  if(r=="exit")
    break
  f.write(r)
f.close()

Enter ddeeff and exit and enter aabbcc Insert picture description here
from the result. The document contains ddeeffaabbcc to know that this write operation is additionalInsert picture description here

3. Read operation

'''
使用try:...except:...进行异常处理,则不会抛出错误,取而代之的是自己定义输出内容,可以对用户更友好。
'''
try:
  f=open(r"C:\User\a\Desktop\physon\龚正讲话.txt","r")
  for text in f:
    print(text)
  f.close()
except:
  print("文件找不到,请核实文件路径")


When the path is correct, the result is: Insert picture description here
If the path is incorrect, the result is:Insert picture description here

Guess you like

Origin blog.csdn.net/Doigt_/article/details/108614258