実行環境
- Cloud9
- Windows7
- Python 2.7
困っていること
- 同じ階層にあるextract.pyをjavascript_kindle.pyにimportしても、そのモジュール内の変数 (filelistnameとindex) がなぜか片方 (index) 使えない。
- importしたモジュール内の変数indexを使う行で
Undefined valuable "index"
と出る (赤い×印の行)
python:extract.py
1# extract.py 2# -*- coding:utf-8 -*- 3# codesフォルダのファイル名を取得 4# [_]以降のファイル名を取得 5# print() する 6import os 7# ファイルパスも文字列! 8# basename = os.path.basename("./codes") codesとフォルダ名が返ってきた 9 10def extract_last(): 11 filelist = os.listdir("./codes") 12 global filelistname 13 filelistname = filelist[0] 14 # [_]以降のファイル名を取得 15 global index 16 index = filelistname.find('_') 17 print(filelistname) 18 print(str(index)) 19 print(filelistname[index:]) # 2番目から末尾までの文字を取り出す
python:javascript_kindle.py
1# javascript_kindle.py 2# -*- coding:utf-8 -*- 3 4import os 5import extract 6files = os.listdir('./codes') 7filenum = len(files) + 1 8 9with open('./output.txt', 'w+') as f: 10 for i in range(1, filenum): 11 file_data = open('./codes/page' + str(i) + extract.filelistname[index:], 'r') 12 # スラッシュの数は24個 13 # ''と""の使い分け: どちらでもよいが、どちらかに統一 14 f.write('////////////////////////\n//page' + str(i) + extract.filelistname[index:] + '\n' + file_data.read() + '\n')
試したこと (しかしうまくいかない)
- Python 外部ファイルで定義した変数を使用したい を参考にfilelistname変数とindex変数をglobal で定義。
- 上記変更後、extract.pyを保存。
よろしくお願いしますm(_)m
できました! ありがとうございます(≧∀≦)
umyu様、ありがとうございますヽ(゚▽゚*)乂(*゚▽゚)ノ
python:extract.py
1# extract.py 2# -*- coding:utf-8 -*- 3 4import glob 5import os 6 7filelistname = "" 8index = 0 9def extract_files(path, ext): 10 for file_name in sorted(glob.glob(path + "/*" + ext)): 11 print(file_name) # ./codes/page1_script.js 12 yield file_name
python:javascript_kindle.py
1# javascript_kindle.py 2# -*- coding:utf-8 -*- 3 4import os 5import extract 6files = os.listdir('./codes') 7filenum = len(files) + 1 8 9with open('./output.txt', 'w+') as f: 10 for file_name in extract.extract_files("./codes", ".js"): 11 with open(file_name, 'r') as file_data: 12 f.write('/' * 24 + '\n//' + os.path.basename(file_name) + '\n' + file_data.read() + '\n')
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/03 11:13 編集
2018/08/04 22:39
2018/08/05 06:03
2018/08/05 11:47