第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定

文件的創(chuàng)建,寫入,關(guān)閉,刪除

標(biāo)簽:
Python

例子1:

#创建文件
context = '''hello world
hello China'''
f = open('hello.txt','w')    #打开文件,若想保存在不同路径,格式为f = open('d:/file/hello.txt','w')
f.write(context)    #把字符串写入文件
f.close()    #关闭文件

程序运行后,会在此程序报存路径上,自动生成一个hello.txt文件,并将context中的内容写入hello.txt文件中,若已有同名文件,会将此文件中的内容清除,再将内容写入。
例子2:按行读取readline()

f = open('hello.txt')    
while True:
    line = f.readline()    #line = f.readline(2)每行每次读2个字符,直到行末尾
    if line:
        print("line")
    else:
        break
f.close()

例子3:多行读取 readlines()

f = open('hello.txt')
lines = f.readlines()
for line in lines:
    print(line)

例子4:一次性读取 read()

f = open('hello.txt')
context = f.read()
print(context)

例子5:使用writelines()写文件

f = open("hello.txt","w+")
li = ["hello world\n","hello china\n"]
f.writelines(li)
f.close()

或者

f = open("hello.txt","w+")
li = "hello world \n hello China\n"
f.write(li)
f.close()

例子6:追加

f = open("hello.txt","a+")
new_context = "goodbey"
f.write(new_context)
f.close()

使用writelines()写文件的速度更快,若需要写入文件的字符串非常多,可以使用writelines()方法提高效率,如需要写入少量的字符串,使用write()方法即可
例子7:删除文件

import os
if os.path.exists("hello.txt"):
    os.remove("hello.txt")

或者

import os
try:
    if os.path.exists("hello.txt")
    os.remove("hello.txt")
except:
    pass #不知何时会执行到except语句

或者

import os
open("hello.txt","w")
try:
    if os.path.exists("hello.txt"):
        os.remove("hello.txt")
except:
    pass

或者

import os
f = open("hello.txt","w") #存在hello.txt文件,会清除内容,不存在hello.txt文件,会生成一个空文件
try:
    if os.path.exists("hello.txt"):
        os.remove("hello.txt")
except:
    pass
點(diǎn)擊查看更多內(nèi)容
3人點(diǎn)贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊有機(jī)會得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消