簡體   English   中英

如何在python中寫入和讀取文件?

[英]How to write and read to a file in python?

到目前為止,我的代碼如下:

restart = 'y'
while (True):
    sentence = input("What is your sentence?: ")
    sentence_split = sentence.split() 
    sentence2 = [0]
    print(sentence)
    for count, i in enumerate(sentence_split): 
        if sentence_split.count(i) < 2:
            sentence2.append(max(sentence2) + 1)
        else:
            sentence2.append(sentence_split.index(i) +1)
    sentence2.remove(0)
    print(sentence2)
    outfile = open("testing.txt", "wt")
    outfile.write(sentence)
    outfile.close()
    print (outfile)
    restart = input("would you like restart the programme y/n?").lower()
    if (restart == "n"):
            print ("programme terminated")
            break
    elif (restart == "y"):
        pass
    else:
        print ("Please enter y or n")

我需要知道該怎么做才能使我的程序打開一個文件,保存輸入的句子以及重新創建該句子的數字,然后能夠打印該文件。 (我猜這是閱讀的部分)。 您可能會說,我對讀取和寫入文件一無所知,因此請寫下您的答案,以便菜鳥可以理解。 同樣,與文件相關的代碼的一部分是在黑暗中從不同網站獲取的完整信息,所以不要以為我對此有所了解。

基本上,您可以通過打開文件對象來創建文件對象,然后執行讀取或寫入操作

從文件中讀取一行

#open("filename","mode")
outfile = open("testing.txt", "r")
outfile.readline(sentence)

從文件中讀取所有行

for line in fileobject:
    print(line, end='')

使用python編寫文件

outfile = open("testing.txt", "w")
outfile.write(sentence)

簡而言之,要在python中讀取文件,您需要以讀取模式“打開”文件:

f = open("testing.txt", "r")

第二個參數“ r”表示我們打開文件進行讀取。 在擁有文件對象“ f”之后,可以通過以下方式訪問文件的內容:

content = f.read()

要使用python寫入文件,您需要以寫入模式(“ w”)或追加模式(“ a”)“打開”文件。 如果選擇寫入模式,則文件中的舊內容將丟失。 如果選擇附加模式,新內容將被寫入文件的末尾:

f = open("testing.txt", "w")

要將字符串s寫入該文件,我們使用write命令:

f.write(s)

在您的情況下,可能類似於:

outfile = open("testing.txt", "a")
outfile.write(sentence)
outfile.close()

readfile = open("testing.txt", "r")
print (readfile.read())
readfile.close()

我建議您遵循cricket_007所指出的官方文檔: https ://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM