栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

文件的创建,写入,关闭,删除

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

文件的创建,写入,关闭,删除

例子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 worldn","hello chinan"]
f.writelines(li)
f.close()

或者

f = open("hello.txt","w+")
li = "hello world n hello Chinan"
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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/226087.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号