0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Windowsのtreeをpathに変換するコードを書いてみた。

Posted at

PCを初期化したとき、初期の構造を記憶するためにディレクトリ構造を取得したくて取得したのだが、
dir C:\\* /s /b /adで取得すればいいものを
treeで取得してしまった。

でも今更もっかい初期化とかできないし。どうしよう。
そうだ、唯一使えるPythonを使ってPath化しよう!

ということで書いた。

コード

ちなみに私はインデントにタブを使っている。タブが好きだからだ。クソコードごめんね

import os


class DirectoryTreeChangeToPath:

	def __init__(self, path):
		paths = self.shaping(self.get_file_content(path))
		with open(".\\changed_directory_tree_to_path.txt","x") as f:
			for i in paths:
				f.write(i + "\n")

	@staticmethod
	def get_file_content(path, mode="r", encoding='utf-8'):
		if os.path.exists(path):
			with open(path, mode=mode, encoding=encoding) as f:
				for i in f:
					yield i
		else:
			raise FileNotFoundError

	@staticmethod
	def shaping(default_dir_tree_data):
		directory = [next(default_dir_tree_data)[:-2]]
		for i in default_dir_tree_data:
			i = i.replace("\n", "", -1)
			i = DirectoryTreeChangeToPath.pipe_count(i)
			DirectoryTreeChangeToPath.merge(directory,i)
			yield "\\".join(directory)

	@staticmethod
	def merge(subject_,object_):
		if len(subject_) > object_[0]:
			del subject_[object_[0]:]
		return subject_.append(object_[1])

	@staticmethod		
	def pipe_count(string):
		indent = 0
		while True:
			if string[:2] in ("└─","├─"):
				string = string[2:]
				indent += 1
				break
			elif string[:3] == "":
				string = string[3:]
				indent += 1
			elif string[:4] == "    ":
				string = string[4:]
				indent += 1
		return indent,string


def main():
	os.chdir(os.path.dirname(__file__))
	DirectoryTreeChangeToPath(".\\infomation\\default_dir_tree_data")


main()

書いてる間の思考

パイプをただのインデントとしてみたら簡単に数値に置換できた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?