2016-04-05 11 views
-1

最も基本的なコードであっても、私の.txtファイルは空になりますが、その理由を理解できません。私はpython 3でこのサブルーチンを実行して、ユーザーから情報を収集しています。メモ帳とN ++の両方で.txtファイルを開くと、空のファイルが表示されます。ここでファイルへの書き込みは機能しません

は私のコードです:

def Setup(): 
    fw = open('AutoLoader.txt', 'a') 

    x = True 

    while x == True: 
     print("Enter new location to enter") 
     new_entry = str(input('Start with \'web\' if it\'s a web page\n')) 
     fw.write(new_entry) 

     y = input('New Data? Y/N\n') 

     if y == 'N' or y == 'n': 
      fw.close 
      break 

    fw.close 
    Start() 
+4

問題はありませんが、 'fw.close'はファイルを閉じません! 'fw.close()'はそうです。 – deceze

+1

'Start()'とは何ですか? –

+2

この問題は、どのように実行されているかに応じて、 'close'である可能性があります。ファイルが正しく閉じられていないため、Ashがエディタでファイルを開くと、データがバッファに存在する可能性があります。 –

答えて

1

は(fw.closeでfw.close交換してみてください)

1

それはそれは、Start()が何をするか知らないのpython 3.4

def Setup(): 
fw = open('AutoLoader3.4.txt', 'a+') 
x = True 
while x == True: 
    print("Enter new location to enter") 
    new_entry = str(input('Start with \'web\' if it\'s a web page\n')) 
    fw.write(new_entry) 

    y = input('New Data? Y/N\n') 

    if y == 'N' or y == 'n': 
     fw.close() 
     break 
fw.close() 
Setup() 
0

をしなければならない作業です答えで無視されて、今のところ...

私はf自分自身ではなく、withステートメントを正しく実行してください。

次のスクリプトは、少なくとも作品:

#!/usr/bin/env python3 

def Setup(): 
    with open('AutoLoader.txt', 'a') as fw: 
     while True: 
      print("Enter new location to enter") 
      new_entry = str(input("Start with 'web' if it's a web page\n")) 
      fw.write(new_entry + "\n") 
      y = input('New Data? Y/N\n') 
      if y in ['N', 'n']: 
       break 

     #Start() 


Setup() 

参照:

[email protected]:~/temp$ ./test_script3.py                             
Enter new location to enter 
Start with 'web' if it's a web page 
First user's entry 
New Data? Y/N 
N 
[email protected]:~/temp$ ./test_script3.py 
Enter new location to enter 
Start with 'web' if it's a web page 
Another user's entry 
New Data? Y/N 
N 
[email protected]:~/temp$ cat AutoLoader.txt 
First user's entry 
Another user's entry 
[email protected]:~/temp$ 

はまた、おそらく行方不明AutoLoader.txtは、起動時に自動的に作成されることに注意してください。

関連する問題