제가 dataset 만들때 하던게 생각나서 문제 작성합니다!
랜덤으로 1, 2, 3 중 하나를 내용으로 갖는 txt 파일100개를 한 디렉토리 안에 생성하는 코드를 작성하시오. ( 파일 제목은 4자리 정수를 랜덤으로 할당. ex - 1382.txt , 0201.txt , 9012.txt , ......... )
제목이 0000~3333 인 txt 파일은 low 폴더로, 3334~6666인 txt 파일은 mid 폴더로, 6667~9999 인 파일은 high 폴더로 이동시키는 코드를 작성하세요. ( 폴더 생성도 코드 안에서 구현 )
low, mid, high 폴더 안에 제목이 1, 2, 3 인 폴더를 각각 만들고, txt 파일 안의 내용에 따라 txt파일을 폴더안으로 이동시켜 분류하세요.
현재 디렉토리 - low - 1, 2, 3 ->1번폴더안의 Txt파일은 전부다 내용에 1 이라고 적혀있음. - mid - 1, 2, 3 - high - 1, 2, 3
5개의 풀이가 있습니다.
from random import randrange, choice
from math import ceil
from pathlib import Path
import shutil
#1
dirpath = Path('dataset')
if not dirpath.exists():
dirpath.mkdir()
for _ in range(100):
filename = '{:04}'.format(randrange(10000))+'.txt'
Path(dirpath/filename).write_text(choice('123'))
#2
for subdir in ['high', 'mid', 'low']:
(dirpath/subdir).mkdir(exist_ok=True)
# dataset/*.txt => dataset/high/, dataset/mid/, dataset/low
for filepath in dirpath.glob('*.txt'):
fn = int(str(filepath.relative_to(dirpath).with_suffix('')))
subdir = 'low' if fn <= 3333 else ('mid' if fn <= 6666 else 'high')
shutil.move(str(filepath), str(dirpath/subdir)) # don't care overwriting
#3
for subdir in ['high', 'mid', 'low']:
subdirpath = dirpath/subdir
for subsubdir in '123':
(subdirpath/subsubdir).mkdir(exist_ok=True)
# dataset/high/*.txt => dataset/high/1, dataset/high/2, dataset/high/3, same for mid and low
for filepath in subdirpath.glob('*.txt'):
subsubdir = filepath.read_text().strip(' \n\r')
if subsubdir in list('123'):
shutil.move(str(filepath), str(subdirpath/subsubdir))
else:
print(filepath, ': invalid file content')
from random import randrange
import glob, os, shutil
path = 'x:/xxxx'
def problem1():
for i in range(100):
with open('{}/{:04}.txt'.format(path, randrange(10000)), 'w', encoding = 'utf8') as wf:
print(randrange(1,4), end = '', file = wf)
def problem2():
f = ['/low', '/mid', '/high']
for i in f:
if not os.path.isdir(path+i):
os.makedirs(path+i)
for i in glob.iglob(path+'/*.txt'):
name = int(os.path.basename(i)[:-4])
idx = (name-1)//3333
shutil.move(i, path+'{}'.format(f[0 if idx < 0 else idx]))
def problem3():
for j in ['/low', '/mid', '/high']:
for i in '123':
if not os.path.isdir('{}{}/{}'.format(path, j, i)):
os.makedirs('{}{}/{}'.format(path, j, i))
for i in glob.iglob(path+j+'/*.txt'):
with open(i, 'r', encoding = 'utf8') as rf: x = rf.read()
shutil.move(i, '{}{}/{}'.format(path, j, x))
Random inputR = new Random();
for (int j = 0; j < 100; j++) {
String contents = "";
contents += inputR.nextInt(3) + 1;
String fileName = "";
for (int i = 0; i < 4; i++) {
fileName += inputR.nextInt(10);
} //파일 이름 생성
String fileLink = "";
if (Integer.parseInt(fileName) <= 3333) {
fileLink += "low\\";
} else if (Integer.parseInt(fileName) <= 6666) {
fileLink += "mid\\";
} else {
fileLink += "high\\";
}
if (contents.equals("1")) {
fileLink += "1\\" + fileName + ".txt";
} else if (contents.equals("2")) {
fileLink += "2\\" + fileName + ".txt";
} else {
fileLink += "3\\" + fileName + ".txt";
}
File f = new File(fileLink);
f.getParentFile().mkdirs();
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(fileLink));
bw.write(contents);
bw.close();
} catch (IOException e1) {
}
}
import random
import shutil
import os
count = 0
if os.path.isdir('low') == True:
shutil.rmtree('low')
if os.path.isdir('mid') == True:
shutil.rmtree('mid')
if os.path.isdir('high') == True:
shutil.rmtree('high')
os.mkdir('low')
os.mkdir('mid')
os.mkdir('high')
for i in range(1,4):
os.mkdir('low\\'+str(i))
os.mkdir('mid\\'+str(i))
os.mkdir('high\\'+str(i))
while count < 100:
filename = ''
for i in range(0,4):
filename = filename+str(random.randint(0,9))
text = str(random.randint(1,3))
if(int(filename) < 3334):
with open('low\\'+text+'\\'+filename+'.txt','w') as w:
w.write(text)
elif(int(filename) > 3333 and int(filename) < 6667):
with open('mid\\'+text+'\\'+filename+'.txt','w') as w:
w.write(text)
else:
with open('high\\'+text+'\\'+filename+'.txt','w') as w:
w.write(text)
count += 1
파이썬3입니다.
from random import randrange
from pathlib import Path
from bisect import bisect_left
s = set()
gs = (3333, 6666)
# 파일 100개 생성
for name, value in ((randrange(1000,10000), randrange(1, 4)) for _ in range(100)):
if name not in s:
s.add(name)
with open('{}.txt'.format(name), 'w') as f:
f.write(str(value))
# 3개 디렉토리 생성
ds = [Path(s) for s in 'low mid high'.split(' ')]
for d in ds:
if not d.exists():
d.mkdir()
# 이름별로 파일 이동
for name in s:
p = Path(f'{name}.txt')
move(p, ds[bisect_left(gs, name)]/p)
# 각 디렉토리 내에서 다시 값별로 파일이동
for d in ds:
xs = [d/Path(str(i+1)) for i in range(3)]
for x in xs:
x.mkdir()
for p in d.glob('*.txt'):
with open(p) as f:
data = f.read()
move(p, xs[int(data)-1]/p.name)