[英]Reading from a file and writing to another file
我對我正在從事的項目有疑問。 我試圖在 inte.net 上搜索我的問題的答案,但找不到任何答案。 所以我在這里.. 我有一個 txt 文件,里面有問題(在彼此下面),我想一一向用戶提出這些問題。 提出問題時,我希望用戶提供輸入(“Y”或“N”)。 如果答案是“Y”或“N”,我想將提出的問題和給出的輸入寫在另一個空的 txt 文件中。 如果答案既不是“Y”也不是“N”,我想打印給定的輸入無效,在打印語句之后,我想再次問同樣的問題。
輸入后,我想再次重復這個過程,但是下一個問題,直到我用完我的 txt 文件中的問題。
我知道它並不多,但現在這是我的代碼:
def import_vragenlijst():
with open ("vragen.txt", "r") as rf:
lezen = rf.readline()
print(lezen)
# with open ("antwoorden_gebruiker.txt", "w") as wf:
def main():
# naam()
import_vragenlijst()
if __name__ == "__main__":
main()
你想把任務分解成更小的部分,你可以單獨處理。
除非您預計會有一個巨大的問題列表,否則請考慮將整個列表讀入一個數組。 同樣,在嘗試將答案寫入文件之前考慮將答案寫入數組,除非出於某種原因需要在用戶回答時寫入它們。
所以你會有這樣的東西(未經測試,不要假設它會在你不付出努力的情況下工作):
def query_user(question):
response = input(question)
if is_valid(response):
return response
else:
print(f'{response} is not valid, must by "Y" or "N"')
# recur, asking the user again
return query_user(question)
def is_valid(response):
return response == "Y" or response == "N"
def main():
# open up the file, then read all the questions into memory
with open(question_filename, "r") as questions_file:
questions = [question for question in questions_file.read()]
# create an array of answers based on user input
answers = [query_user(question) for question in questions]
# open the answers file and write the questions and answers out
with open(answered_questions_filename, "w") as answers_file:
for question, answer in zip(questions, answers):
answers_file.writeline(question)
answers_file.writeline(answer)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.