首页 > 解决方案 > 有什么方法可以根据文件的一行打印特定的字符串?

问题描述

所以我目前正在尝试在我为学校项目制作的基于文本的卡片战斗器中打印卡片列表,我想知道是否可以获得一些帮助。如果文件中的一行是 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"))

标签: python

解决方案


这就是我要做的(更新):

# 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

希望这会有所帮助!


推荐阅读