怎么新建MySQL数据库

发布时间:2022-08-22 作者:admin
阅读:436
在这篇文章中,我们来学习一下“Python中对文件的操作怎样实现,有哪些方法”的相关知识,下文有详细的讲解,易于大家学习和理解,有需要的朋友可以借鉴参考,下面就请大家跟着小编的思路一起来学习一下吧。


文件的操作(打开,读,写,重命名,删除等)

1,打开文件(open)

open('文件名','r') : 只读方式打开文件

open('文件名','r+') : 以读写方式打开,文件不存在报错

open('文件名','w') : 可写方式打开文件

open('文件名','w+') : 以读写方式打开,文件不存在新建

open('文件名','a') : 以追加写方式打开,文件不存在新建

open('文件名','a+') : 以追加读写方式打开,文件不存在新建

open('文件名','rb') : 以二进制读方式打开,只能读文件 , 如果文件不存在,会发生异常

open('文件名','wb') : 以二进制写方式打开,只能写文件 , 如果文件不存在则创建

fr = open('test.txt','r') # 只读
fr_ = open('test.txt','r+') # 读写,不创建
fw = open('test.txt','w') # 只写,创建
fw_ = open('test.txt','w+') # 读写,创建
fa = open('test.txt','a') # 追加写,创建
fa_ = open('test.txt','a+') # 追加读写,创建
frb = open('test.txt','rb') # 二进制读,不创建
fwb = open('test.txt','wb') # 二进制写,创建


2,写数据(write)

使用write()可以完成向文件写入数据,如果文件不存在那么创建,如果存在那么就先清空,然后写入数据

f = open('test.txt','w') # 打开test.txt文件,如果没有就新建,w文件可写
f.write('hello world') #写入hello world,覆盖原先的全部数据
f.close() # 关闭文件


3,读数据(read)

使用read(num)可以从文件中读取数据,num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据

f = open('test.txt','r') # 打开test.txt文件,如果没有就新建,w文件可写
content = f.read(5)  # 最多读取5个数据
print(content) # hello
print('*'*10)
content = f.read()  # 从上次读取的位置继续读取剩下的所有的数据
print(content) #  world
f.close() # 关闭文件


4,读数据(readlines)

就像read没有参数时一样,readlines可以按照行的方式把整个文件中的内容进行一次性读取,并且返回的是一个列表,其中每一行的数据为一个元素

f = open('test.txt','w')
f.write('hello world\nhello world\nhello world\nhello world\nhello world') # 写入5行hello world

f = open('test.txt', 'r')
content = f.readlines()
print(type(content))
print(content)

i=1
for con in content:
    print("%d:%s" % (i, con))
    i += 1
f.close()
'''
运行结果
<class 'list'>
['hello world\n', 'hello world\n', 'hello world\n', 'hello world\n', 'hello world']
1:hello world

2:hello world

3:hello world

4:hello world

5:hello world
'''


4,文件重命名

os模块中的rename()可以完成对文件的重命名操作

import os
os.rename("test.txt", "test2.txt")


5,删除文件

os模块中的remove()可以完成对文件的删除操作

import os
os.remove("test2.txt")

到此这篇关于“Python中对文件的操作怎样实现,有哪些方法”的文章就介绍到这了,更多相关内容请搜索群英网络以前的文章或继续浏览下面的相关文章,希望大家以后多多支持群英网络!

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。

二维码-群英

长按识别二维码并关注微信

更方便到期提醒、手机管理

7*24 全天候服务

售前 400-678-4567

售后 0668-2555666

售后 400 678 4567

信息安全 0668-2555 118

域名空间 3004329145