簡體   English   中英

重命名一個新文件,當有相同名稱的文件時,沒有限制名稱

[英]Rename a new file when there in file with the same name without limited name

我寫了一個代碼來創建一個文本文件並寫一些東西。 但是當代碼再次啟動時,它會覆蓋一個文件並刪除舊文本。 我知道 append 方法,但我想在新文件中保存新文本。 我導入 pathlib 但它對許多重命名都不好:

from pathlib import path

ExampleName = path(./example.txt)
if ExampleName.exist():
   ExampleName = path(./example2.txt)

with open(example_name, mode= 'w') as t_file:
    t_file.write('blah blah blah')
    t_file.close()

我也使用時間模塊。 它比 pathlib 好,但我想創建從 1 到 up 的文件,而不是隨機的 extream:!! 數字:

import time

AppendName = str(time.time())

with open(f'./example{AppendName}.txt', mode='w') as t_file:
    t_file.write('blah blah blah')
    t_file.close()

在這種情況下,我無法識別哪個文本文件比另一個文件舊。

可能不是你想要達到的,試試這樣:

from datetime import datetime
from pathlib import Path


def file_checker(file):
    if Path(file).exists():
        with open(file, 'r') as file1, open(f'{file}-{datetime.now()}', 'a') as file2:
            file2.write(file1.read())
            file2.write('\nblah blah blah')


file_checker('example.txt')

或與shutil類似:

from datetime import datetime
from pathlib import Path
import shutil


def file_checker(file):
    if Path(file).exists():
        new_file_name = f"{file}-{datetime.now()}"
        shutil.copyfile(file, new_file_name)
        with open(new_file_name, 'a') as new_file:
            new_file.write('\nblah blah blah')
    else:
        with open(file, 'w') as file1:
            file1.write('blah blah blah')


file_checker('example.txt')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM