python 3.7极速入门教程6文件解决

作者 : 开心源码 本文共1551个字,预计阅读时间需要4分钟 发布时间: 2022-05-12 共132人阅读

6文件解决

文件读写

创立文本文件

f= open("china-testing.github.io.txt","w+")for i in range(10):     f.write("This is line %d\n" % (i+1))f.close() 

Open需要2个参数,要打开的文件和表示文件执行的权限或者操作的种类字符串,这里”w” 表示写入和加号表示假如文件中不存在则会创立。常用的选项 还有 “r”表示读取, “a”用于追加。

for循环使用write函数将数据输入到文件中。我们在文件中迭代的输出是 “this is line number”,%d表示显示整数。

最后关闭存储的文件的实例。

图片.png

附加文件

f= open("china-testing.github.io.txt","a+")for i in range(2):     f.write("Appended line %d\n" % (i+1))f.close() 

图片.png

读取文件

f= open("china-testing.github.io.txt","r")contents =f.read()print(contents)

图片.png

基于行读取文件

for line in  open("china-testing.github.io.txt"):    print(line)

图片.png

相似代码:

f = open("china-testing.github.io.txt")for line in f.readlines():    print(line)

文件操作模式小结

模式形容
‘r’默认模式。 读。
‘w‘此模式打开文件进行写入。假如文件不存在,则会创立新文件。假如文件存在,则会先清空文件。
‘x’创立文件。 假如文件已存在,则操作失败。
‘a‘在附加模式下打开文件。假如文件不存在,则会创立新文件。
‘t’默认模式。 它以文本模式打开。
‘b’以二进制模式打开。
‘+’打开文件进行读写(升级)

判断文件或者者目录能否存在

os.path.exists(path)

import os.pathprint ("File exist:"+str(os.path.exists('china-testing.github.io.txt')))print ("File exists:" + str(os.path.exists('github.io.txt')))print ("Directory exists:" + str(os.path.exists('myDirectory')))

图片.png

os.path.isfile()

import os.pathprint ("Is it File?" + str(os.path.isfile('china-testing.github.io.txt')))print ("Is it File?" + str(os.path.isfile('myDirectory')))

图片.png

os.path.isdir()

import os.pathprint ("Is it Directory?" + str(os.path.isdir('china-testing.github.io.txt')))print ("Is it Directory?" + str(os.path.isdir('..')))

图片.png

pathlibPath.exists()

import os.pathprint ("Is it Directory?" + str(os.path.isdir('china-testing.github.io.txt')))print ("Is it Directory?" + str(os.path.isdir('..')))

图片.png

文件拷贝

比较常用的有:

shutil.copy(src,dst)shutil.copystat(src,dst)

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » python 3.7极速入门教程6文件解决

发表回复