![](/img/trans.png)
[英]How do I detect if my user has uploaded an ImageField or FileField?
[英]How do I detect if a user is using my file for the first time?
我正在制作一個Python文件,我想要一個不同的屏幕顯示給第一次打開文件的人,而不是一個重復訪問者。 像這樣:
if USER_NEW:
print('New user screen')
else:
print('other screen')
究竟我該怎么做呢?
當您的腳本再次運行時,您需要將信息存儲在另一個文件中以便稍后閱讀。 當您運行腳本時,您需要閱讀此文件並查看是否包含一個值,表示訪問者已查看該文件或寫入該文件以告知程序在下次訪問期間何時擁有該文件。
例如:
with open('user.txt', 'r+') as file:
if file.read() == '':
print('New user screen')
else:
print('other screen')
file.write('visited')
您可以將程序信息保存在狀態文件中。 這樣做取決於操作系統,即使這樣你也會發現不同意見。 在Windows上,您可以使用環境變量%LOCALAPPDATA%
。 在大多數unixy系統上你可以使用~/.myapp
或者~/.config/myapp
(我更喜歡第二種)。 我不知道其他機器上的約定。
您還需要為文件格式建立約定。 我只想找一個文件名。
import platform
import os
import time
if platform.system() == "Windows":
my_app_path = os.path.expandvars("%LOCALAPPDATA%/myapp")
elif platform.system() == "Linux":
my_app_path = os.path.expanduser("~/.config/myapp")
else:
exit(2)
first_run_file = os.path.join(my_app_path, "first_run.txt")
if not os.path.exists(first_run_file):
first_run = True
os.makedirs(my_app_path)
open(first_run_file, "w")
else:
first_run = False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.