簡體   English   中英

如何使用python讀取和寫入文件?

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

我想將文本(我從 AJAX 獲得)寫入文件,然后讀取它。

如果你可以在 Django 視圖中使用它......試試這樣的想法:

def some_view(request):
    text = request.POST.get("text", None)
    if text is not None:
        f = open( 'some_file.txt', 'w+')
        f.write(text)
        f.close()
    return HttpResponse()
f = open( 'filename.txt', 'w+' )
f.write( 'text' )
f.close()

f = open( 'filename.txt', 'r' )
for line in f:
    print( line )
f.close()

以下代碼用於從文件中讀取內容

handle=open('file','r+')
var=handle.read()
print var

如果您想讀取一行,請使用 readline()。 如果你想閱讀文件中的整行,也可以使用 readlines()

以下代碼用於將內容寫入文件

handle1=open('file.txt','r+')
handle1.write("I AM NEW FILE")
handle1.close()

你可以試試這個

with open("file.txt", "r+") as file:

     for i in file:
         file.write(i + "\n")
file.close

暫無
暫無

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

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