Write, read, copy, batch rename files in python

1. Write the content to the file

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. Read the contents of the file

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

3. Copy the file

'''
思路:
    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. Batch rename
1) Environment preparation

    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) Program part

'''
思路:
    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) Execution result part

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325344760&siteId=291194637