1. Writing content to a 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. Copying files
‘‘‘思路: 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 [[email protected] test]# cd /appdata/test/;touch {1..10}.txt;lltotal 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 section
‘‘‘思路: 1.获取要重命名的文件的文件夹路径 2.获取所有要重命名的文件 3.执行重命名‘‘‘import osdef 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 Results section
python rename_batch.py 请输入要重命名文件的文件夹路径:/appdata/test1.txt/appdata/test/huwho出品-1.txt2.txt/appdata/test/huwho出品-2.txt3.txt/appdata/test/huwho出品-3.txt4.txt/appdata/test/huwho出品-4.txt5.txt/appdata/test/huwho出品-5.txt6.txt/appdata/test/huwho出品-6.txt7.txt/appdata/test/huwho出品-7.txt8.txt/appdata/test/huwho出品-8.txt9.txt/appdata/test/huwho出品-9.txt10.txt/appdata/test/huwho出品-10.txt
Implement write, read, copy, batch rename files in Python