2016-02-23 67 views
0

運行

我正在Python版本3.5,從命令提示符在Windows 7Python - 爲什麼我的.read()不能在我的.txt文件上工作?沒有什麼是輸出到CMD線

什麼是.txt文件,什麼CMD輸出

What the cmd prompt outputs

What the .txt contains

我當前的代碼

"""Opens a file and let\'s you read it and write to it""" 

open_pls = open("text.txt", "a+") 

#Main function 
def read_write(): 
    program_running = True 
    while program_running == True: 
     choice = input("Write R for read, write W for write or write X for exit:") 
     choice = choice.upper() 
     if choice == "W": 
      what_write = input("What do you want to write to the end of the file?:") 
      open_pls.write(what_write) 
      print("Succesfully written!") 
      print("Running program again...") 
      continue 
     elif choice == "R": 
      print("This file contains:") 
      read_pls = open_pls.read() 
      print(read_pls) 
      print("Running program again...") 
      continue 
     elif choice == "X": 
      program_running = False 
      open_pls.close() 
     else: 
      print("That was not a valid command!") 
      print("Running program again...") 
      continue 

run = input("Run the program? (Y/N):") 
run = run.upper() 
if run == "Y": 
    read_write() 
elif run == "N": 
    input("Exit program? Press enter:") 
else: 
    input("Exit program? Press enter:") 

我認爲問題出在某處這裏

elif choice == "R": 
     print("This file contains:") 
     read_pls = open_pls.read() 
     print(read_pls) 
     print("Running program again...") 
     continue 

回答

0

當您使用'a'追加模式打開文件時,操作系統將爲您提供一個文件位置在文件末尾的文件。

你可以嘗試尋求回到開始第一,但是這取決於您的操作系統如果這實際上將被允許:

open_pls.seek(0) 
read_pls = open_pls.read() 

您可能希望'r+'模式來打開文件,而不是,並尋求寫作結束時。

+0

謝謝,我現在明白了:) –

0

當你打開一個文件,'a'模式,該文件旨在結束。要獲取文件的內容,您必須回到起點:open_pls.seek(0)

+0

''a''確實**不會**截斷文件。這是該模式的重點,你可以追加。但文件位置設置爲結尾,所以寫入實際上會附加。 –

+0

糟糕;抱歉。我編輯了我的答案。 – zondo

+0

謝謝,我現在明白了:) –

相關問題