-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathipynb_CONVERTER_forCheatSheet.py
More file actions
63 lines (53 loc) · 2.78 KB
/
ipynb_CONVERTER_forCheatSheet.py
File metadata and controls
63 lines (53 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import json, os # , sys
def convert_ipynb_to_py(ipynb_file, output_file=None):
if not ipynb_file.endswith('.ipynb'):
print("Please provide a valid .ipynb file.")
return
try:
with open(ipynb_file, 'r', encoding='utf-8') as f:
notebook = json.load(f)
code_lines = []
for cell in notebook.get('cells', []):
if cell.get('cell_type') == 'code':
# code_lines.append("# Cell\n")
code_lines.extend(cell.get('source', []))
code_lines.append("\n\n")
elif cell.get('cell_type') == 'markdown':
# code_lines.append("# Markdown\n")
code_lines.append('"""\n')
code_lines.extend(cell.get('source', []))
code_lines.append('\n"""\n\n')
else:
# code_lines.append(f"# {cell.get('cell_type')}\n")
code_lines.append("'''\n")
code_lines.extend(cell.get('source', []))
code_lines.append("\n'''\n\n")
if not code_lines:
print("No code cells found in the notebook.")
return
# Determine the output file name
if output_file is None:
output_file = os.path.splitext(ipynb_file)[0] + ".py"
with open(output_file, 'w', encoding='utf-8') as f:
f.writelines(code_lines)
print(f"Conversion complete. Python file saved as: {output_file}")
except Exception as e:
print(f"Error converting file: {e}")
# convert_ipynb_to_py(
# ipynb_file = r"C:\Users\JonathanChackoPattas\OneDrive - Maritime Support Solutions\Desktop\Class Notes\Seneca\Semester 2\AIG200 - Capstone Project\Individual Submission - Machine Learning Model Deployment Assignment\notebooks\create_model_reference.ipynb",
# output_file = r"C:\Users\JonathanChackoPattas\OneDrive - Maritime Support Solutions\Desktop\Class Notes\Seneca\code.py"
# )
# folderpath = "C:\\Users\\JonathanChackoPattas\\OneDrive - Maritime Support Solutions\\Desktop\\Class Notes\\Seneca\\Semester 1\\AIG150 - Data Preparation and Governance\\Cheat_Sheet_Maker\\Solution Files\\"
# for files in os.listdir(os.path.join(folderpath, "Teacher Given")):
# if files.endswith(".ipynb"):
# convert_ipynb_to_py(
# ipynb_file = os.path.join(folderpath, "Teacher Given", files),
# output_file = os.path.join(folderpath, "Converted", files[:-6] + ".py")
# )
# if __name__ == "__main__":
# if len(sys.argv) < 2:
# print("Usage: python convert_ipynb_to_py.py <notebook_file.ipynb> [output_file.py]")
# else:
# ipynb_file = sys.argv[1]
# output_file = sys.argv[2] if len(sys.argv) > 2 else None
# convert_ipynb_to_py(ipynb_file, output_file)