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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值