for root, dirs, files in os.walk("path/to/folder"):
for filename in files:
if "1" in filename:
do_something()
else:
do_something_else()
os.walk
을 사용하면 디렉토리 트리의 생성자를 반환합니다. 같은 테스트 디렉토리를 상상해
C:\temp
| \subdir
| | subfile1.txt
| | subfile2.txt
| file1.txt
| file2.txt
list(os.walk)
생산됩니다
말을하는 것입니다
[("C:\\temp", ["subdir"], ["file1.txt","file2.txt"]),
("C:\\temp\\subdir", [], ["subfile1.txt","subfile2.txt"])]
는, 각각의 반복은 원래 인수의 각 하위 디렉토리에 대한 root, list_of_directories_in_root, list_of_files_in_root
을 생산하고 있습니다. 당신이 정말로 root
또는 dirs
걱정하지 않는다, 그러나 당신이 파일의 이름을 변경 (또는 등) 경우 적어도 필요합니다
for root, dirs, files in os.walk("path/to/folder"):
가 지금은 사실이다 : 따라서 우리는 os.walk
에 걸쳐 같은 방법으로 반복 os.rename(os.path.join(root, filename), "newname.txt")
을 수행 할 것이므로 root
입니다.
파일의 * 내용 *에서 '1'을 찾으시겠습니까? 제 튜토리얼 (https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)을 읽어야합니다. – jonrsharpe