您的位置:首页 > 编程语言 > Python开发

在python中实现对文件的写入,读取,复制,批量重命名

2018-05-06 16:20 1276 查看
1.写入内容至文件中

def write_file():
open_file = open("xxxx.txt","w")
open_file.write("i want to open a file and write this.\n")
open_file.close()
write_file()

2.读取文件中的内容

#思路:1.以什么方式打开 2.读取文件 3.关闭文件
def read_file():
read_file = open("xxxx.txt","r")
content = read_file.read()
print(content)
read_file.close()
read_file()

3.复制文件

'''
思路:
1.获取用户要复制的文件名
2.执行复制
2.1打开要复制的文件名
2.2新建一个文件
2.3从旧文件中读取数据,并且写入到新文件中
3.关闭文件
'''
def copy_file():
#1.获取用户要复制的文件名
old_file_name = input("请输入要复制的文件名:")

#2.1打开要复制的文件名
old_file = open(old_file_name,"r")

#2.2新建一个文件名
position = old_file_name.rfind(".")
new_file_name = old_file_name[:position] + "[复件]" + old_file_name[position:]
new_file = open(new_file_name,"w")

#2.3从旧文件中读取数据,并且写入到新文件中
while True:
content = old_file.read(1024)
if len(content) == 0:
break
new_file.write(content)

#关闭文件
old_file.close()
new_file.close()
copy_file()

4.批量重命名
1)环境准备

mkdir /appdata/test/
cd /appdata/test/;touch {1..10}.txt;ll
[root@localhost test]# cd /appdata/test/;touch {1..10}.txt;ll
total 0
-rw-r--r-- 1 root root 0 May  6 15:59 10.txt
-rw-r--r-- 1 root root 0 May  6 15:59 1.txt
-rw-r--r-- 1 root root 0 May  6 15:59 2.txt
-rw-r--r-- 1 root root 0 May  6 15:59 3.txt
-rw-r--r-- 1 root root 0 May  6 15:59 4.txt
-rw-r--r-- 1 root root 0 May  6 15:59 5.txt
-rw-r--r-- 1 root root 0 May  6 15:59 6.txt
-rw-r--r-- 1 root root 0 May  6 15:59 7.txt
-rw-r--r-- 1 root root 0 May  6 15:59 8.txt
-rw-r--r-- 1 root root 0 May  6 15:59 9.txt

2)程序部分

'''
思路:
1.获取要重命名的文件的文件夹路径
2.获取所有要重命名的文件
3.执行重命名
'''

import os

def rename_batch():
#1.获取文件夹
folder_name = input("请输入要重命名文件的文件夹路径:")

#2.获取所有文件名
file_names = os.listdir(folder_name)

#3.重命名
for name in file_names:
print(name)
old_file_name = folder_name + "/" + name
new_file_name = folder_name + "/" + "huwho出品-" + name
os.rename(old_file_name,new_file_name)
print(new_file_name)
rename_batch()

3)执行结果部分

python rename_batch.py
请输入要重命名文件的文件夹路径:/appdata/test
1.txt
/appdata/test/huwho出品-1.txt
2.txt
/appdata/test/huwho出品-2.txt
3.txt
/appdata/test/huwho出品-3.txt
4.txt
/appdata/test/huwho出品-4.txt
5.txt
/appdata/test/huwho出品-5.txt
6.txt
/appdata/test/huwho出品-6.txt
7.txt
/appdata/test/huwho出品-7.txt
8.txt
/appdata/test/huwho出品-8.txt
9.txt
/appdata/test/huwho出品-9.txt
10.txt
/appdata/test/huwho出品-10.txt
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 文件操作