1. ディレクトリの内容をリストし、そのリスト (temp.txt) を作成し、リストを文字列に変換してファイルに書き込むスクリプトを作成しようとしています 2. 他のテキスト ファイル (t .txt) を開き、開いたファイルの内容を以前に保存したファイル (temp.txt) と比較し、その差を返します。アイデアは、フォルダーに新しいファイルがあるかどうかをスクリプトが判断できるようにすることです。関数 dif はスタンドアロン スクリプトとしてはうまく機能しますが、関数としてネストすると、次のエラー メッセージが表示されます。
Enter directory > /users
Traceback (most recent call last):
File "/Users/alkopop79/NetBeansProjects/comparefiles.py", line 33, in <module>
dir()
File "/Users/alkopop79/NetBeansProjects/comparefiles.py", line 12, in dir
li.append(fname)
UnboundLocalError: local variable 'li' referenced before assignment
そしてスクリプト:
import os
li = []
lu = []
le = []
def dir():
dir = raw_input("Enter directory > ")
path=dir # insert the path to the directory of interest
dirList=os.listdir(path)
for fname in dirList:
li.append(fname)
li = ','.join(str(n) for n in li)
targetfile = open("temp.txt", 'w')
targetfile.write(li)
targetfile.close()
print li
def open_file():
txt = open('t.txt')
li = txt.read()
la = li.split()
return la
print len(li)
def open_another():
txt = open('temp.txt')
lu = txt.read()
lo = lu.split()
return lo
print len(li)
dir()
a = open_file()
b = open_another()
print set(a) & set(b)