在Windows中以编程方式复制、重命名和粘贴文件的最佳方法

2024-09-30 08:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录C:\HotFolders,其中应用程序每15分钟写入一次csv文件,文件名格式为YYYYMMDDhhmmss_DG@001991.csv.

我需要复制新文件(在创建新文件时),并将它们粘贴到另一个目录中,只需对文件名(_dgto _GWL)做一点小小的更改

我最初尝试制作一个SSMS包 (此处描述:https://jimsalasek.com/2017/03/15/ssis-create-extract-file-with-date-and-time-for-a-filename/) 要查询SQL数据库,请生成相同的文件并导出到目录,但SQL版本控制问题导致在SSMS中运行SSIS包(.dtsx文件)暂时无法运行

我尝试了一些python脚本来实现这一点(见下文),但扫描目录以查找最新的文件、复制并按计划粘贴重命名的文件(比如每5分钟一次)让我陷入了困境

我知道批处理和powershell也是可选的,甚至第三方软件,我也欢迎使用。我只需要一些关于最佳方法的指导,任何代码都会很感激

Python代码片段

import os
files = [os.path.join('C:\\test', x) for x in os.listdir('C:\\test') if x.endswith(".csv")]
newest = max(files , key = os.path.getctime)```




Tags: 文件csvpath代码test目录应用程序for
2条回答
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory, destination directory, target directory,
rem batch directory, filenames, output filename and temporary filename [if shown] are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "destdir=u:\your results"

:again

:: Find latest converted
SET "latest=20000000000000"
FOR /f "delims=_" %%b IN ('dir /b /a-d /o-n "%destdir%\*_GWL*.csv" 2^>nul' ) DO (SET "latest=%%b"&GOTO gotlatest)
:gotlatest

FOR /f "delims=" %%b IN ('dir /b /a-d /o-n "%sourcedir%\*_DG*.csv" 2^>nul') DO (
 FOR /f "tokens=1*delims=_" %%q IN ("%%b") DO IF "%%q" gtr "%latest%" (
  rem for each later file
  SET "filenametail=%%r"
  ECHO COPY "%sourcedir%\%%b" "%destdir%\%%q_GWL!filenametail:~2!" 
  COPY "%sourcedir%\%%b" "%destdir%\%%q_GWL!filenametail:~2!" >nul 
  ECHO Press X or Q to EXIT %~n0
 ) ELSE GOTO wait
)

:wait
:: wait 300 sec (5 min)
choice /c xqc /n /t 300 /d c >nul
IF ERRORLEVEL 3 GOTO again

ECHO Process %~n0 EXIT...

GOTO :EOF

评注应足以解释

希望我能很好地理解,这就是你想要的:

Function Rename-Stuff{
Get-ChildItem -Path "C:\HotFolders" | Foreach {Rename-Item $_.FullName -NewName $_.Name.Replace("_DG","_GWL")} 
    Foreach($file in (Get-ChildItem -Path "C:\HotFolders")){ Move-Item -Path $file.FullName -Destination "C:\New\Path\Here"}
    Start-Sleep 360
    &Rename-Stuff}

请让我知道这是否是你一直在寻找的,如果你想了解发生在这个短脚本块;我非常乐意解释(只是不想假设你还不知道一切)

哎呀,刚刚意识到你想复制这些项目:

Function Copee-Stuff{
Copy-Item -Path "C:\HotFolders" -Recurse -Destination "C:\New\Path\Here" 
    Foreach($file in (Get-ChildItem -Path "C:\New\Path\Here")){ Rename-Item $file.FullName -NewName $file.Name.Replace("_DG","_GWL")}
    Start-Sleep 360
    &Copee-Stuff}

请注意:您还可以按csv或-Filter参数提供的任何其他文件扩展名进行筛选

相关问题 更多 >

    热门问题