We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,695 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Copying all Files with New Name

Hi,

I actually want to copy the contents of all files that is in a
particular directory into a new directory.The new files should be of a
specific size (2MB)and each with a new name (randomly assigned).

My Current Code looks,

testdir = "K:/test"
# Iterating over each entry
Dir.entries(testdir).each do |file|

# Joining the path where the files are

path = File.join testdir, file
if File.file? path
File.open path
File.copy(file,'K:/t1')
# NOTE: t1 file doesn't exist assuming
will create itself? probably wrong

end
end
end

When simply trying to copy using File.copy(to,from) it gives following
error message "No such file or directory K:/"

Do you think this approach is completely wrong ?
Any suggestions about giving random names for the new files..?

Many Thanks,

2
Contributors
2
Replies
1 Day
Discussion Span
3 Years Ago
Last Updated
3
Views
hawksury
Newbie Poster
3 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

http://userpages.umbc.edu/~dhood2/courses/cmsc433/spring2010/?section=Notes&topic=Ruby&notes=07

The above is a good resource.

As far as your code, it looks ok, except you should be passing the file name to the File.file? method. Like

File.file?(aFile) then if it is actually a regular file, rename it.

BestJewSinceJC
Posting Maven
2,774 posts since Sep 2008
Reputation Points: 874
Solved Threads: 354
Skill Endorsements: 13

Thanks ,the link to the resource you gave was very helpful.
I can copy the files now, but when i am putting a restriction on a file size it doesn't care about the restriction and copies beyond the placed restriction.. My program logic is probably incorrect..! Here is the code,

Dir.entries(testdir).each do |file|
# Joining the path where the actual files are
path = File.join testdir, file
if File.file? path
File.open path do |source|
while (line=source.gets)
File.open("K:/testresult/test1.txt",'a') do |dest|
# Trying to put a restriction here if size of file is < 50
if File.size("K:/testresult/test1.txt")<50
dest.puts(line)
else
File.open("K:/testresult/test2.txt",'a')
dest.puts(line)
end
end
end end
It isn't giving any error message works fine but it is copying the file contents even if the file.size is beyond what i specified <50

hawksury
Newbie Poster
3 posts since Apr 2010
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.2850 seconds using 2.64MB