繁体   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