如何使用Python正确搜索文件目录以获取特定详细信息

时间:2018-02-09 07:16:13

标签: python python-3.x file

我是Python新手并试图找出我当前程序中出错的地方。我正在尝试编写它以便检查特定的文本文件(“HomeInventory.txt”)并根据它是否存在执行不同的任务。例如,如果确实存在,则理想情况下会询问用户是否要添加到已存在的数据中,如果不存在,则询问他们是否要创建新文件。我认为我所拥有的是接近我,但它似乎永远不会认识到该文件确实存在。任何帮助是极大的赞赏。这是我的代码:

from pathlib import Path

tupleRow = ( "","" )
tupleTable = ()
while(True):

  # Obtain user input (2 different variables)
  nameVal = str(input("Enter the name of a household item: "))

  inputName = str(nameVal).upper()

  inputValue = float(input("Enter the value of your item: "))

  # Format values entered to appear like currency
  # NOTE: Because I use float as input, I only need one "0"
  # at the end

  tempVal = str(inputValue)
  finalVal = "$" + tempVal + "0"

  # Stores each new input into it's correct tuple
  tupleRow = (inputName, finalVal)

  # 2. Ask the user for new entries and stores
  #    them in the 2-dimensional Tuple.

  continueMsg = str(input("Do you have more items to enter? Y/N: ").upper())

  if(continueMsg == "Y"):
        continue
  else:
        break

tupleTable += tupleRow
myFile = Path("%~dp0HomeInventory.txt")

if(myFile.is_file() == False):

  createFile = str(input("HomeInventory.txt does not exist yet, do you want to create it? Y/N: ").upper())

  if(createFile == "Y"):

        objFile = open("HomeInventory.txt", "a+")
        # Conditional Header
        for line in objFile:

              if ("Item, Value" in line):
                    objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
                    objFile.close()
              else:
                    row0 = str("Item, Value")
                    objFile.write(str(row0 + '\n'))
                    objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
                    objFile.close()

  else:
        print("Y'all come back later. Y'hear? ")

elif(myFile.is_file() == True):

  overrideMsg = str(input("HomeInventory.txt already exists. Save new data here? Y/N: ").upper())

  if(overrideMsg == "Y"):
        objFile = open("HomeInventory.txt", "a")

        # Conditional Header
        for line in objFile:

              if ("Item, Value" in line):
                    objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
                    objFile.close()
              else:
                    row0 = str("Item, Value")
                    objFile.write(str(row0 + '\n'))
                    objFile.write(str(tupleTable).strip("(" ")" "'" "'"))
                    objFile.close()

  else:
        print("Y'all come back later. Y'hear? ")

2 个答案:

答案 0 :(得分:0)

您可以使用os模块

import os.path
if os.path.isfile(full_path_to_file):

答案 1 :(得分:0)

import os.path
if os.path.isfile('../index.html'):
    print "available";
else:
    print "not available";

想象一下父文件夹中可用的文件index.html。为此,我们可以这样检查。 如果文件在脚本相同的目录中,那么代码就像这样

import os.path
if os.path.isfile('index.html'):
    print "available";
else:
    print "not available";

我希望它会对你有所帮助!