2016-04-05 23 views
-1

En temel kodla bile .txt dosyası boş çıkıyor ve nedenini anlayamıyorum. Kullanıcıdan bilgi toplamak için bu alt yordamı python 3'da çalıştırıyorum. Not defteri ve N ++ hem de .txt dosyasını açtığımda boş bir dosya alıyorum. İşte Bir dosyaya yazma çalışmaz

benim kod:

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

Sorununuz değil, ancak 'fw.close' dosyanızı kapatmıyor! 'fw.close()' yapar. – deceze

+1

'Start()' ne yapar? –

+2

Bu işlemin nasıl yapıldığına bağlı olarak _could_ "clos" (sorun) olur. Dosya düzgün bir şekilde kapatılmadığından, Ash dosyayı bir düzenleyicide açtığında veriler bir arabellekte olabilir. –

cevap

1

fw.close() ile fw.close değiştirmeyi deneyin Start(), bu gerekeni yapar bilmeden 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

Cevaplar göz ardı edilmemelidir, şu ana kadar ...

ile kendim, ama bir with bildirimi işi düzgün yapalım.

ardından komut en az çalışır:

#!/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() 

Bkz:

[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$ 

Ayrıca muhtemelen eksik AutoLoader.txt başlangıcında otomatik olarak oluşturulur olacağını unutmayın.