python - 有什么方法可以根据文件的一行打印特定的字符串?
问题描述
所以我目前正在尝试在我为学校项目制作的基于文本的卡片战斗器中打印卡片列表,我想知道是否可以获得一些帮助。如果文件中的一行是 0 或 1,我正在尝试打印不同的内容,但我无法弄清楚。谢谢,如果你能帮忙
def mainfunc():
while i<cardlist:
#if it's zero, do this
print("the card this line represents")
#if it's one, do this
print("locked")
#else, becasue if it's else then you're at the end of the file
print("your deck:")
#print your current deck
print("which card do you want to add?")
print(filelinecount("RIPScards"))
解决方案
这就是我要做的(更新):
# For preventing unwanted behavior if this file ever gets imported in another:
if __name__ == "__main__":
with open(**insert file path here**, 'r') as f:
for line in f:
if line.strip() == "0":
print("the card this line represents")
elif line.strip() == "1":
print("locked")
else:
print("your deck")
print("which card do you want to add?")
print(filelinecount("RIPScards"))
您可以像这样打开文件逐行读取文件:
with open(**file path**, 'r') as f:
for line in f:
# Do stuff with the line here
或者您可以一次读取所有行并关闭文件,然后对这些行进行处理,如下所示:
f = open(**file name here**, 'r')
$lines = f.readlines()
f.close() # Make sure to close it, 'with open' method automatically does that for you, but manually opening it (like in this example) will not do it for you!
# Do stuff with it:
for line in lines:
# Do something with the line
希望这会有所帮助!
推荐阅读
- php - PHP:将对象转换为以对象属性为键的关联数组
- python - Elastic Beanstalk is not installing requirements.txt file
- javascript - 启动反应应用程序时出错
- jenkins - 通过 jenkins 从 kafka 队列中检索消息数
- javascript - 失败:无法读取未定义的属性“querySelector” - 业力茉莉
- clion - 如何在 CLion 2018.2 中切换工具链?
- javascript - 设置 width : 0 不隐藏文本
- excel - 使用单元格值过滤日期之间的数据透视表
- c# - 我正在尝试在 C# 中创建一个插件来验证 mailItem.Body 以避免特定内容,但是当我发送消息时我的事件没有激活
- jquery - 首次打开后引导模式不起作用