python - ~~由于创建一个新文件,循环在 Python 中死去~~ 读/写问题已解决
问题描述
当我启动我的电脑时,我正在无限循环上运行一个 python 文件。该脚本将数据保存到 txt 文件中,我正在阅读它以查看我获得的数据是否已经获得。我尝试了许多不同的读/写类型,r+ w+ a+,如果文件不存在......脚本停止。我正在打印文本文件的内容,如果尚未创建,则循环不会打印任何内容。这也可能是 .read() 的问题?我尝试使用 .seek(0) 无济于事。
这是代码的文件写入部分:
def is_online_unique(streamer):
file_contents = 'Null'
is_online_new = False
file_name = streamer + "Streams.txt"
with open(r'D:\StreamerDates\\' + file_name , 'a+') as current_file:
current_file.seek(0)
r = requests.get(url=API_ENDPOINT+streamer, headers=head)
data = r.text
#print(data.replace('"', '').replace('\'', '').split(','))
if 'type' in data and 'live' in data:
clean_data = data.replace('"', '').replace('\'', '').split(',')
for string in clean_data:
if 'started_at' in string:
date_started = string
print("Date Started = " + date_started)
try:
file_contents = current_file.read()
except:
print('Error in reading file somehow :P')
print("File contents:" + file_contents)
if date_started in file_contents:
is_online_new = False
else:
is_online_new = True
if is_online_new:
current_file.write(date_started + '\n')
elif len(file_contents) > 500:
if os.path.exists(r'D:\StreamerDates\\' + file_name):
os.remove("demofile.txt")
current_file.close()
return is_online_new
主要:
while(True):
for streamer in streamers:
if is_online_unique(streamer):
url = 'twitch.tv/' + streamer
#print(streamer + "\'s stream opened")
webbrowser.get(windowsChromePath).open(url)
解决方案
您正在打开文件
with open(r'D:\StreamerDates\\' + fileName , 'a+') as currentFile:
使用“a+”,这意味着您可以将数据附加到文件中,而不是读取,要读取您将必须有另一个
with open(r'D:\StreamerDates\\' + fileName , 'r') as currentFile:
但使用 'r' 这样您就可以读取其中的数据
您也不需要 a声明为您执行此currentFile.close()
操作with
原来我在这里有点错误'a +'确实读过。 链接到模式
我认为问题在于您正在创建一个新文件,并将datestarted
变量写入其中,但仅在IsOnline is True
. 在文件中IsOnline
时变为真。datestarted
所以它永远不会写,读不会返回任何东西,这就是我认为你所看到的。它没有错,文件中没有任何内容
推荐阅读
- android - 不知道如何用语言表达。我的应用程序在它应该将一个元素放在飞机上然后没有响应时出现故障
- python - 我想开发一个使用 gcc 编译和运行 c 程序的 python 脚本
- wordpress - 即使在更改值、手动更新或编辑 apache 配置后,Wordpress 永久链接也不起作用
- javascript - 节点 S3 将所有具有相似前缀的对象发回给我
- python-3.x - 抓取时登录超时
- android - 如何即时订购数据
- c++ - 如何更新变量以及如何在程序重新启动后获得更新的值?
- apache-spark - Spark Caching - 数据分发和复制
- android - 来自未知开发者的应用有时可能不安全
- java - 有没有办法将基于文本的游戏放在 jframe 窗口中