让程序实现文件的读取与写入。
文件内容编辑
打开文件
f
= open('test.txt','w')
访问模式说明
r只读,默认打开方式w写入或创建a在原文末尾追加r/w/a+b二进制格式打开一个文件
关闭文件
f
.close
()
写数据
f
.write
('Hello World')
>>>11
读数据
read
f
= open('test.txt','r')
content
= f
.read
(11)
print(content
)
f
.close
()
>>>Hello World
readlines
f
= open('test.txt')
f
.readlines
()
f
.close
()
readline
f
= open('test.txt')
f
.readline
()
f
.close
()
定位
f
.tell
()
f
.seek
(100,1)
数字大方向
0文件开头1当前位置2文件末尾
综合运用:文件备份程序
f
= open('test.nb.txt','w')
f
.write
('Hello World')
f
.close
()
old_file_name
= input('请输入你要备份的文件的文件名: ')
name
= old_file_name
.rsplit
('.',1)
str = '[备份].'
name
= str.join
(name
)
'''
#2. 备份源文件_第二种方法
position = old_file_name.rfind('.')
name = old_file_name[0:position]+'[备份]'+old_file_name[position:]
'''
f2
= open(name
,'w')
f
= open(old_file_name
,'r')
while True:
content
= f
.read
(1024)
if len(content
)==0:
break
f2
.write
(content
)
f
.close
()
f2
.close
()
f2
= open(name
,'r')
content
= f2
.read
(50)
print(content
)
f2
.close
()
文件操作
重命名
import os
os
.rename
('test.txt','test_final.txt')
删除
import os
os
.remove
('test_final.txt')
文件夹操作
创建文件夹
import os
os
.mkdir
('Python')
删除文件夹
import os
os
.rmdir
('Python')
获取当前目录
import os
os
.getcwd
()
>>>D
:\\Python
查看当前目录下所有文件名
import os
os
.listdir
()
>>>[ 'test.nb.txt', 'test.nb[备份].txt', 'test.txt']
改变默认目录
import os
os
.chdir
('D:\\Python\\233')
综合运用:批量重命名文件
'''
#批量创建旧文件
import os
os.chdir('D:\\Python\\233')
os.mkdir('renames')
os.chdir('D:\\Python\\233\\renames')
i = 1
while True:
f = open('新三国-%d.txt'%i,'w')
f.close()
i+=1
if i>10:
break
'''
import os
os
.chdir
('D:\\Python\\233')
folder_name
= input('请输入要重命名的文件夹:')
file_names
= os
.listdir
(folder_name
)
os
.chdir
(folder_name
)
for name
in file_names
:
print(name
)
os
.rename
(name
,'[东哥出品]-'+name
)
answer
= os
.listdir
('D:\\Python\\233\\renames')
print(answer
)
转载请注明原文地址: https://mac.8miu.com/read-495881.html