第七篇 系统读写文件操作

 1 #读写文件
 2 #Windows上使用倒斜杠\ OSX和linux上使用正斜杠/
 3 
 4 #(1)字符串链接 os.path.join
 5 import os
 6 myFiles = ['accounts.txt','details.csv','invite.docx']
 7 for myFile in myFiles:
 8     print(os.path.join('C:\\users\\aswitgart',myFile))
 9 
10 #os.path.join函数作用是用正确的分隔符链接字符串,构建所有操作系统上都有效的路径
11 
12 #(2)当前工作目录
13 #获取当前目录os.getcwd()   改变当前目录os.chdir()
14 #绝对路径:从根文件夹开始
15 #相对路径:相对于程序的当前工作目录
16 
17 #(3)os.makedirs()创建新文件夹
18 
19 #(4)os.path模块
20 #os.path.abspath('.') 返回参数的绝对路径的字符串
21 #os.path.isabs(path) 判断参数是否是绝对路径,是true  否 false
22 #os.path.relpath(path,start)返回从start路径到path的相对路径的字符串
23 #os.path.dirname(path)它返回path参数中最后一个斜杠之前的所有内容,就是除了文件名所有的内容,当前目录
24 #os.path.basename(path)它返回path参数中最后一个斜杠之后的所有内容,实质就是文件名
25 #os.path.split(paht) 它得到上面两个字符串的元组,当前目录和文件名的元组
26 #os.paht.sep 变量设置为正确的文件夹分割斜杠
27 
28 #(5)查看文件大小和文件夹内容
29 #os.path.getsize(path)将返回path参数中文件的字节数
30 #os.listdir(path)返回文件名字符串的列表
31 #如果想知道这个目录下所有文件的总字节数,可以同时使用os.path.getsize和os.listdir
32 totalSize = 0
33 for filename in os.listdir('C:\\Windows\\System32'):
34     totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32',filename))
35 print(totalSize)
36 
37 #(6)检查路径的有效性
38 #如果path参数所指的文件或文件夹存在,调用os.path.exists(path)将返回true,否则返回false
39 #如果path参数存在,且是一个文件,调用os.path.isfile(path)将返回true
40 #如果path参数存在,且是一个目录,调用os.path.iddir(path)将返回true
41 
42 #文件读写过程
43 '''
44 在Python中,读写文件有3个步骤:
45 1.调用open()函数,返回一个file对象
46 2.调用file对象的read()或write()方法
47 3.调用file对象的close()方法,关闭该文件
48 '''
49 helloFile = open('C:\\hello.text','w')
50 helloFile.write("Hello Word!")
51 helloFile.close()
52 helloFile = open('C:\\hello.text','a')
53 helloFile.write("I must Success!")
54 helloFile.close()
55 helloFile = open('C:\\hello.text','r')
56 helloFile.readlines()  #读出的文件放在列表中,以/n进行分割
57 helloFile.close()
58 
59 
60 #使用shelve模块保存变量
61 #创建shelve文件
62 import shelve
63 shelfFile = shelve.open('mydata')
64 cats = ['zophie','Pooka','Simon']
65 shelfFile['cats'] = cats
66 shelfFile.close()
67 #打开读取shelve文件
68 shelfFile = shelve.open('mydata')
69 type(shelfFile)  #-->输出文件类型
70 shelfFile['cats']  #-->输出字典内容
71 list(shelfFile.keys())#-->输出所有的键
72 list(shelfFile.values())#-->输出所有的值
73 shelfFile.close()#关闭文件
74 
75 
76 #利用pprint.pformat()函数保存变量
77 import pprint
78 cats = [{'name':'Zophie','desc':'chubby'},{'name':'Pooka','desc':'fluffy'}]
79 pprint.pformat(cats)  #---》转成字符串的形式
80 fileObj = open('myCats.py','w')
81 fileObj.write('cats = '+pprint.pformat(cats) + '\n')
82 fileObj.close()
83 
84 import myCats
85 myCats.cats  #---->输出保存的列表内容
86 myCats.cats[0] #--->输出列表第一个内容
87 myCats.cats[0]['name']#---输出字典键name的值

猜你喜欢

转载自www.cnblogs.com/qilvzhuiche/p/9053464.html