[英]Cant get text to append to file in python
好的,所以這段代碼是Flask服務器內部的http響應。 我認為此信息沒有任何用處,但如果您需要知道的話,也可以使用。
假定此代碼從發布請求中讀取名稱並寫入文件。 然后,它檢查一個名為saved.txt的文件,該文件存儲在FILES字典中。 如果在saved.txt文件中找不到文件名,則將文件名附加到保存的文件中。
APIResponce函數只是一個json轉儲
目前,它似乎根本沒有添加。 該文件寫得很好,但追加無法通過。
順便說一句,這正在Linux發行版的Linino上運行。
def post(self):
try:
## Create the filepath so we can use this for mutliple schedules
filename = request.form["name"] + ".txt"
path = "/mnt/sda1/arduino/www/"
filename_path = path + filename
#Get the data from the request
schedule = request.form["schedule"]
replacement_value = schedule
#write the schedule to the file
writefile(filename_path,replacement_value)
#append the file base name to the saved file
append = True
schedule_names = readfile(FILES['saved']).split(" ")
for item in schedule_names:
if item == filename:
append = False
if append:
append_to = FILES['saved']
filename_with_space =filename + " "
append(append_to,filename_with_space)
return APIResponse({
'success': "Successfully modified the mode."
})
except:
return APIResponse({
'error': "Failed to modify the mode"
})
這是要求的功能
def writefile(filename, data):
#Opens a file.
sdwrite = open(filename, 'w')
#Writes to the file.
sdwrite.write(data)
#Close the file.
sdwrite.close()
return
def readfile(filename):
#Opens a file.
sdread = open(filename, 'r')
#Reads the file's contents.
blah = sdread.readline()
#Close the file.
sdread.close()
return blah
def append(filename,data):
## use mode a for appending
sdwrite = open(filename, 'a')
## append the data to the file
sdwrite.write(data)
sdwrite.close()
布爾對象附加和函數名稱附加是否相同? 當我嘗試它時,Python抱怨“ TypeError:'bool'對象不可調用”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.