<p>按照您的方法(使用检查目录是否存在的函数等),您可以执行以下操作:</p>
<pre><code>import os
import shutil
from time import gmtime, strftime
def copyFile(old_path, new_directory):
# check if the directory already exists
if not os.path.exists(new_directory):
os.mkdir(new_directory)
print(f"Directory {new_directory} Created.")
else:
print(f"Directory {new_directory} already exists.")
# create new path from new_directory, the filename and the timestamp
new_path = new_directory + old_path.split("/")[len(old_path)-1].split(".")[0] + strftime("%Y_%m_%d", gmtime()) + ".csv"
# copy the file to the new path
try:
shutil.copy(old_path, new_path)
# eg. src and dest are the same file
except shutil.Error as e:
print(f"Error: {e}")
# eg. source or destination doesn't exist
except IOError as e:
print(f"Error: {e.strerror}")
old_path = '/path/to/directory/file.csv'
new_directory = '/path/to/new/directory/'
copyFile(old_path, new_directory)
</code></pre>
<p>请注意</p>
<ol>
<li>从python3.6开始,可以使用f字符串更容易地在字符串中包含变量。你知道吗</li>
<li>我不清楚你在找什么样的时间戳。
这种方法将给您一个<code>YYYY_MM_DD</code>格式的戳记
但是你可以很容易地改变,看到了吗
<a href="https://docs.python.org/3/library/time.html#time.strftime" rel="nofollow noreferrer">documentation</a>在<code>time</code>包上。你知道吗</li>
<li>使用<code>shutil.copy</code>之后,您不再需要<code>shutil.move</code>,因为
第一个已复制了您的文件并将其保存到目标
路径。你知道吗</li>
</ol>