groovy copy files with same last modified date - file

Hi I want to copy a file from 1 directory to another, but the date has to be the same. so when the last modified date in the fromdirectory is 14:35, I want it to be the same in the todirectory.
How can I do this using groovy?

Using AntBuilder
new AntBuilder().copy ( file : 'path/to/source',
tofile : 'path/to/destination',
preservelastmodified : 'true' )
Using Java/Groovy File API
def source = new File ('path/to/source')
def destination = new File ('path/to/destination')
source.withInputStream { is ->
destination << is
}
destination.lastModified = source.lastModified()

Related

SSIS Archiving a file

I have an SSIS package that outputs a csv file what I want to do is look in the destination folder before I generate a csv and if one already exists (I produce them on a daily basis ) then move it to an archive folder.
my file name structure is "NAME_YYMMDD_HHMM.csv" I'm not sure how I go about looking for a file as the date and time will always be different. i've created a variable for the filename "NAME_*_.csv but not sure how id add this to a file system task? if a file doesn't exist id like it to just move on to next step in package if it does exist then move file to archive folder
You should use a script task to do this:
Use a variable in string file instead which holds your values from YYMMDD since HHMM is unable to get when you created it run time.
Date formats can be found here
Use namespace using System.IO;
string filepath = #"D:\new";
string file = "test_171205_1010.txt";
string fullpath = filepath + #"\" + file;
string newpath = #"D:\arch\";
string newfullpath = newpath + file;
if(
File.Exists(fullpath))
{
File.Move(fullpath, newfullpath);
}
Update
And if you wanna use something about todays date, you can do like below where i look for all files of today and move them. Its up to your what the logic should be.
string txtFile = null;
string txtMoveFile = null;
string date = DateTime.Now.ToString("yyMMdd");
string filepath = #"D:\new";
/*USE THIS LINE IF YOU WANNA USE VARIABLE FROM FOREACH LOOP CONTAINER*/
string file = Dts.Variables["User::name"].Value.ToString() +"_*_*.txt";
//string file = "test_"+date+"_*.txt";
string[] allfilesfromcurrentdate = Directory.GetFiles(filepath, file);
string fullpath = filepath + #"\" + file;
string newpath = #"D:\arch\";
string newfullpath = newpath + file;
foreach(string fileName in allfilesfromcurrentdate)
{
if(fileName.Contains("test_"+date))
{
txtFile = fileName;
txtMoveFile = txtFile.Replace("new", "arch");
if(File.Exists(txtFile))
{
File.Move(txtFile, txtMoveFile);
}
}
}

Python-Change String in file and output all content with the new strings to a new file

i`m trying to scan for a string in all files under a directory and several sub directories , replace it , and when i preformed the replacement save it into a new file,
I managed to
1) search for the string in all the files in the folder and sub folders ,
2) count the amount of appearances of the string
3) create new files for those who had the string .
But for some reason the new files i get are empty , instead of containing the lines of the old files with the replaced string .
Here is my Code :
import os
parentDirectory = "E:\ProjectPython\Test"
oldString = "oldString"
newString = "newString"
if (os.path.isdir(parentDirectory)):
for dirName,directories,files in os.walk(parentDirectory):
for fileName in files:
fullPath = os.path.join(dirName,fileName)
with open(fullPath) as file:
counter=0
for line in file:
if line.__contains__(oldString) or line.__contains__(oldString.lower()):
counter=counter+1
if counter>>0 :
with open(fullPath+".New","w") as newFile:
for line in file:
newFile.write(line.replace(oldString,newString))
print("File:"+fullPath+"\nStrings that were replaced:"+str(counter))
else:
print(parentDirectory+"is missing!")

Handling Hebrew files and folders with Python 3.4

I used Python 3.4 to create a programm that goes through E-mails and saves specific attachments to a file server.
Each file is saved to a specific destination depending on the sender's E-mail's address.
My problem is that the destination folders and the attachments are both in Hebrew and for a few attachments I get an error that the path does not exsist.
Now that's not possible because It can fail for one attachment but not for the others on the same Mail (the destination folder is decided by the sender's address).
I want to debug the issue but I cannot get python to display the file path it is trying to save correctly. (it's mixed hebrew and english and it always displays the path in a big mess, although it works correctly 95% of the time when the file is being saved to the file server)
So my questions are:
what should I add to this code so that it will proccess Hewbrew correctly?
Should I encode or decode somthing?
Are there characters I should avoid when proccessing the files?
here's the main piece of code that fails:
try:
found_attachments = False
for att in msg.Attachments:
_, extension = split_filename(str(att))
# check if attachment is not inline
if str(att) not in msg.HTMLBody:
if extension in database[sender][TYPES]:
file = create_file(str(att), database[sender][PATH], database[sender][FORMAT], time_stamp)
# This is where the program fails:
att.SaveAsFile(file)
print("Created:", file)
found_attachments = True
if found_attachments:
items_processed.append(msg)
else:
items_no_att.append(msg)
except:
print("Error with attachment: " + str(att) + " , in: " + str(msg))
and the create file function:
def create_file(att, location, format, timestamp):
"""
process an attachment to make it a file
:param att: the name of the attachment
:param location: the path to the file
:param format: the format of the file
:param timestamp: the time and date the attachment was created
:return: return the file created
"""
# create the file by the given format
if format == "":
output_file = location + "\\" + att
else:
# split file to name and type
filename, extension = split_filename(att)
# extract and format the time sent on
time = str(timestamp.time()).replace(":", ".")[:-3]
# extract and format the date sent on
day = str(timestamp.date())
day = day[-2:] + day[4:-2] + day[:4]
# initiate the output file
output_file = format
# add the original file name where needed
output_file = output_file.replace(FILENAME, filename)
# add the sent date where needed
output_file = output_file.replace(DATE, day)
# add the time sent where needed
output_file = output_file.replace(TIME, time)
# add the path and type
output_file = location + "\\" + output_file + "." + extension
print(output_file)
# add an index to the file if necessary and return it
index = get_file_index(output_file)
if index:
filename, extension = split_filename(output_file)
return filename + "(" + str(index) + ")." + extension
else:
return output_file
Thanks in advance, I would be happy to explain more or supply more code if needed.
I found out that the promlem was not using Hebrew. I found that there's a limit on the number of chars that the (path + filename) can hold (255 chars).
The files that failed excided that limit and that caused the problem

Find string in log files and return extra characters

How can I get Python to loop through a directory and find a specific string in each file located within that directory, then output a summary of what it found?
I want to search the long files for the following string:
FIRMWARE_VERSION = "2.15"
Only, the firmware version can be different in each file. So I want the log file to report back with whatever version it finds.
import glob
import os
print("The following list contains the firmware version of each server.\n")
os.chdir( "LOGS\\" )
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + " = ???)
I was thinking I could use something like the following to return the extra characters but it's not working.
file[:+5]
I want the output to look something like this:
server1.web.com = FIRMWARE_VERSION = "2.16"
server2.web.com = FIRMWARE_VERSION = "3.01"
server3.web.com = FIRMWARE_VERSION = "1.26"
server4.web.com = FIRMWARE_VERSION = "4.1"
server5.web.com = FIRMWARE_VERSION = "3.50"
Any suggestions on how I can do this?
You can use regex for grub the text :
import re
for file in glob.glob('*.log'):
with open(file) as f:
contents = f.read()
if 'FIRMWARE_VERSION = "' in contents:
print (file + '='+ re.search(r'FIRMWARE_VERSION ="([\d.]+)"',contents).group(1))
In this case re.search will do the job! with searching the file content based on the following pattern :
r'FIRMWARE_VERSION ="([\d.]+)"'
that find a float number between two double quote!also you can use the following that match anything right after FIRMWARE_VERSIONbetween two double quote.
r'FIRMWARE_VERSION =(".*")'

Groovy - create file issue: The filename, directory name or volume label syntax is incorrect

I'm running a script made in Groovy from Soap UI and the script needs to generate lots of files.
Those files have also in the name two numbers from a list (all the combinations in that list are different), and there are 1303 combinations
available and the script generates just 1235 files.
A part of the code is:
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
where $file is actually that part of the file name which include those 2 combinations from that list:
file = "abc" + "-$firstNumer"+"_$secondNumber"
For those file which are not created is a message returned:"The filename, directory name or volume label syntax is incorrect".
I've tried puting another path:
filename = "D:\\rez\\" + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
targetFile.createNewFile();
and also:
File parentFolder = new File("D:\\rez\\");
File targetFile = new File(parentFolder, "$file"+"_OK.txt");
targetFile.createNewFile();
(which I've found here: What are possible reasons for java.io.IOException: "The filename, directory name, or volume label syntax is incorrect")
but nothing worked.
I have no ideea where the problem is. Is strange that 1235 files are created ok, and the rest of them, 68 aren't created at all.
Thanks,
My guess is that some of the files have illegal characters in their paths. Exactly which characters are illegal is platform specific, e.g. on Windows they are
\ / : * ? " < > |
Why don't you log the full path of the file before targetFile.createNewFile(); is called and also log whether this method succeeded or not, e.g.
filename = groovyUtils.projectPath + "\\" + "$file"+"_OK.txt";
targetFile = new File(filename);
println "attempting to create file: $targetFile"
if (targetFile.createNewFile()) {
println "Successfully created file $targetFile"
} else {
println "Failed to create file $targetFile"
}
When the process is finished, check the logs and I suspect you'll see a common pattern in the ""Failed to create file...." messages
File.createNewFile() returns false when a file or directory with that name already exists. In all other failure cases (security, I/O) it throws an exception.
Evaluate createNewFile()'s return value or, additionally, use the File.exists() method:
File file = new File("foo")
// works the first time
createNewFile(file)
// prints an error message
createNewFile(file)
void createNewFile(File file) {
if (!file.createNewFile()) {
assert file.exists()
println file.getPath() + " already exists."
}
}

Resources