내부에 파일이 몇개 담긴 폴더 ex) 직박구리 가 있습니다.
이 폴더를 같은 디렉토리에 통째로 복사하려고 하는데 복사를 진행할때마다 사본, 사본_1, 사본_2 .....처럼 이름을 지으려고 합니다.
만약 사본이라는 폴더가 이미 있으면 사본_1 을,
사본 과 사본_1, 사본_2 가 모두 있다면 사본_3을,
사본 과 사본_2, 사본_3 이 있다면 비어있는 사본_1 을
생성하는 코드를 작성하세요.
13개의 풀이가 있습니다.
from pathlib import Path
import shutil
src = input('폴더명: ')
if not Path(src).exists() or not Path(src).is_dir():
raise Exception(src + ': invalid directory')
# 사본_100 까지만.
for dst in ['사본'] + ['사본_'+str(n) for n in range(1, 101)]:
if not Path(dst).exists():
shutil.copytree(src, dst)
break
import os, shutil
def copycopy(dir, path):
name = os.path.basename(dir)
if not os.path.isdir(os.path.join(path, name)):
shutil.copytree(dir, os.path.join(path, name))
return
idx = 1
while True:
newname = name + '_{}'.format(idx)
if not os.path.isdir(os.path.join(path, newname)):
shutil.copytree(dir, os.path.join(path, newname))
return
idx += 1
copycopy('x:/xxx/folder', 'x:/xxx')
import shutil, os
#print(os.getcwd())
input1 = input("input dir name : ")
postfix=1
folder_list = os.listdir('.')
#for dir in folder_list:
# print(dir)
while True:
newname = input1+'_'+str(postfix)
if newname not in folder_list:
break;
else:
postfix += 1
shutil.copytree(input1, newname)
import os
import shutil
def Making_Name(A):
folder = os.listdir("C:/")
print(folder)
folder.sort()
cnt=0;
for i in folder :
if i.find("사본")==-1 :
result = "사본"
else :
if i.find('_')==-1 :
result = "사본_1"
else :
cnt+=1
if cnt!=int(i[i.find('_')+1:]) :
result ="사본_"+str((cnt))
break
else :
result = "사본_"+ str((cnt+1))
shutil.copytree("C:/"+A, "C:/"+result)
folder_after=os.listdir("C:/")
print("="*130)
print(folder_after)
#폴더 복사하기
import os,shutil
print(os.listdir())
a=1
sub=1
New ='사본'
shutil.copytree('직박구리',New)
while a:
if New in os.listdir():
New ='사본'
New+='_'+str(sub)
sub+=1
shutil.copytree('직박구리',New)
if '사본_3' in os.listdir():
a=0
def folder_copy(folder):
folder_list = ['사본', '사본_1', '사본_2', '사본_3', '비어있는 사본_1']
n = len(folder_list)
for i in range(n-1):
if os.path.isdir(folder_list[i]) is not True:
shutil.copytree(folder, folder_list[i])
return
elif (os.path.isdir(folder_list[i])) is True & (os.path.isdir(folder_list[i+1]) is False):
shutil.copytree(folder, folder_list[i+1])
return
C#: Exception 처리는 생략하였습니다.
using System;
using System.IO;
namespace CD202
{
class Program
{
static void Main(string[] args)
{
CopyFolder cp = new CopyFolder(@"D:\Temp\test");
cp.MakeACopy();
Console.ReadKey();
}
}
class CopyFolder
{
// 원래 폴더 경로
private readonly DirectoryInfo OriginalPath;
// 부모 폴더 경로
private readonly DirectoryInfo ParentPath;
// 사용 가능한 다음 사본 폴더 경로
private DirectoryInfo NextTargetPath
{
get
{
int label = 0;
string nextTargetPathNameTry = "사본";
while (Directory.Exists($"{ParentPath}\\{nextTargetPathNameTry}"))
{
label++;
nextTargetPathNameTry = $"사본_{label}";
}
return new DirectoryInfo($"{ParentPath}\\{nextTargetPathNameTry}");
}
}
public CopyFolder(string originalPath)
{
OriginalPath = new DirectoryInfo(originalPath);
ParentPath = Directory.GetParent(originalPath);
}
// 다음 사본 폴더에 원래 폴더 내용 복사
public void MakeACopy()
{
DirectoryInfo TargetPath = NextTargetPath; // 복사 대상 경로명에 대해
// 원래 경로명 문자열을 대상 경로명 문자열로 치환함에 의해 폴더 및 파일 복사함
// 사본 (하위)폴더 생성
Directory.CreateDirectory(TargetPath.FullName);
foreach (string dirPath in Directory.GetDirectories(OriginalPath.FullName, "*",
SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(OriginalPath.FullName, TargetPath.FullName));
}
// 사본 폴더에 파일 복사
foreach (string filePath in Directory.GetFiles(OriginalPath.FullName, "*.*",
SearchOption.AllDirectories))
{
File.Copy(filePath, filePath.Replace(OriginalPath.FullName, TargetPath.FullName), true);
}
}
}
}
폴더 파일을 사본폴더에 복사하는데 하위 폴더에 있는 파일을 어떻게 복사할지 모르겠습니다.
import java.io.*;
public class Question_2 {
/* 현재 디렉토리 */
static final String DIR = System.getProperty("user.dir");
static boolean b = true;
public static void main(String[] args) {
File dir = new File(DIR);
CreateDir d1 = new CreateDir(dir);
while(b) {
d1.CreateDirectory();
b = false;
}
System.exit(0);
}
}
class CreateDir {
static File dir;
static File temp;
static int count = 0;
static boolean b = true;
CreateDir() {}
CreateDir(File dir) {
this.dir = dir;
}
static void CreateDirectory() {
while(b) {
if(count == 0) {
temp = new File(dir, "사본");
temp.mkdir();
copys(dir, temp);
}
else if(count <= 3) {
temp = new File(dir, "사본" + "_" + count);
temp.mkdir();
copys(dir, temp);
} else if(count > 3) {
temp = new File(dir, "비어있는 " + "사본" + "_" + 1);
temp.mkdir();
copys(dir, temp);
b = false;
}
count++;
}
}
public static void copys(File selectFile, File copyFile) { //복사할 디렉토리, 복사될 디렉토리
File[] filelist = selectFile.listFiles();
for (File file : filelist) {
File temp = new File(copyFile.getAbsolutePath() +"\\"+ file.getName());
if (file.isDirectory()) {
temp.mkdirs();
// copys(file, temp);
// 사용하면 무한루프 발생!! 어떻게 해결하지??
} else {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(temp);
int data = 0;
while((data=fis.read()) != -1) {
fos.write(data);
}
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
directory = list(input().split())
temp = []
for i in directory:
if i == '사본':
temp.append(0)
else:
temp.append(int(i.split('_')[1]))
for i in range(len(directory)):
if i in temp:
continue
else:
directory.append('사본_' + str(i))
if len(temp) == len(directory):
directory.append('사본_' + str(len(temp)))
if '사본_0' in directory:
directory.remove('사본_0')
directory.append('사본')
print(directory)
import os,shutil
print(os.listdir()) a=1 sub=1 New ='사본' shutil.copytree('직박구리',New)
while a:
if New in os.listdir():
New ='사본'
New+='_'+str(sub)
sub+=1
shutil.copytree('직박구리',New)
if '사본_3' in os.listdir():
a=0
from pathlib import Path
import shutil
src = input('폴더명: ')
if not Path(src).exists() or not Path(src).is_dir():
raise Exception(src + ': invalid directory')
# 사본_100 까지만.
for dst in ['사본'] + ['사본_'+str(n) for n in range(1, 101)]:
if not Path(dst).exists():
shutil.copytree(src, dst)
break
import os
import glob
import shutil
def makedir(p):
d = list(filter(os.path.isdir, glob.glob(p+'*')))
n = list(map(lambda m: m[-1][-1], sorted(d)))
if not '본' in n: return '_사본'
elif len(n) == 2 and n[-1] == '본': return '_사본_1'
else:
if int(n[-1])+2 == len(n):
return '_사본_'+str(int(n[-1])+1)
else:
for i in range(1, int(n[-1])):
if not str(i) in n:
return '_사본_'+str(i)
if __name__ == '__main__':
os.chdir('C://python_learning/codingdojang')
p = '직박구리'
md = makedir(p)
shutil.copytree('직박구리', p+md)