Here, we have to input the data from the user, to read the data from user, we use input() method, and then the input data we have to store in the file by using write() method and then by using read() method we can get the data.
在這里,我們必須從用戶輸入數據,從用戶讀取數據,我們使用input()方法,然后我們必須使用write()方法然后使用read( )將輸入數據存儲在文件中)方法即可獲取數據。
Here is the python code to save and read the data:
這是保存和讀取數據的python代碼:
def main():
# open file in write mode
fo = open("data2.txt","wt")
# Input the user data
data = input("Enter Some Data to Save: ")
# write data to the file
fo.write(data)
# close the file
fo.close()
# open file again in read mode
fo = open("data2.txt","rt")
# read the data from the file
str=fo.read()
# print the read data
print("\nThe Content of File is:")
print(str)
# close the file
fo.close()
if __name__=="__main__":main()
Output
輸出量
Enter Some Data to Save: Hello friends, how are you?
The Content of File is:
Hello friends, how are you?
翻譯自: https://www.includehelp.com/python/input-data-from-the-user-save-to-the-file-read-and-print.aspx