我正在运行Python版本3.5,来自Windows 7上的cmd提示
"""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 :(得分:0)
当您使用'a'
模式打开文件时,文件将搜索到最后。要获取文件的内容,您必须回头查看:open_pls.seek(0)
。
答案 1 :(得分:0)
当您使用'a'
追加模式打开文件时,操作系统会为您提供一个文件位于文件末尾的文件。
你可以先尝试回到起点,但这取决于你的操作系统是否真的被允许:
open_pls.seek(0)
read_pls = open_pls.read()
您可能希望以'r+'
模式打开文件,并在撰写时寻求结束。