【问题标题】:Data Path for File Input Processing文件输入处理的数据路径
【发布时间】:2018-01-14 03:11:51
【问题描述】:

我想为 python 提供一个可用于设置输入处理的 Windows“数据路径”。我用谷歌搜索了这个没有运气,现在我想我自己了。

似乎有很多方法可以使用 python 读取文件,在对“\”和“/”以及 windows 路径名感到沮丧之后,我找到了一种方法来设置我的数据路径。这不是一种通用方法,但应该对我有用。

相关问题:这段代码难看吗?这是一种非标准方法吗? 3.6 中有哪些优雅的功能应该使用?

### Title: Process an input file using a 'data path' for a user on windows
import sys 
import os
print("OK, starting program...")

file_processed = False
for path, dirs, files in os.walk("/Users/Mike"):
    if file_processed: break
    for file in files:
        if file_processed: break
        if file == 'seriousdata.txt':
            my_path = os.path.abspath(path)
            my_dsn = os.path.join(my_path, file)
            print("Opening txt file " + my_dsn + " for input.")
            with open(my_dsn) as da_lines:
                textlines = (line.rstrip('\r\n') for line in da_lines)
                for line in textlines:
                    print(line)
            file_processed = True
if file_processed:
    pass
else:
    print("File not found")

print("OK, program execution has ended.")
sys.exit() # END SAMPLE CODE SNIPPET

【问题讨论】:

  • 是否需要遍历整个目录树才能找到severedata.txt?如果您已经知道文件在哪里,那么将路径指定为命令行参数会简单得多。如果您对此有疑问,请查看this answer

标签: python python-3.x file-io


【解决方案1】:

通过查看您的代码,我假设您希望从一个目录开始,然后遍历每个子目录,如果找到匹配的文件名的内容,则打印出来。

如果是这样,那么这是使用递归的方法:

import os

def recursive_list(path, filename):
    files = os.listdir(path)
    for name in files:
        try:
            p = os.path.join(path, name)
            if os.path.isdir(p):
                recursive_list(p, filename)
            else:
                if name == filename:
                    with open(p, "r") as f:
                        print(f.read())
        except PermissionError:
            pass
    return

recursive_list("/home/jebby/Desktop","some_file.txt")

这将开始列出path 中的文件。对于找到的每个文件,如果该文件是一个目录,则调用该函数本身(从该文件夹的路径开始)。如果filename 匹配当前目录中任何文件的名称,则会打印(如果用户对该文件有权限)。

否则,如果您只想从已知目录中读取文件名而不遍历目录树:

import os

data_path = "/home/jebby/Desktop"
file_you_want = "filename.txt"
with open(os.path.join(data_path, file_you_want), "r") as f:
    content = f.read()
print(content)

【讨论】:

  • 我喜欢您的递归代码 - 可以轻松地调整它以搜索从根目录开始的重复项。 (+1)
  • 我知道第二种解决方案,但只是认为我缺少 python 路径、windows 路径、windows env 变量、相对路径等的一些东西,
【解决方案2】:

主要问题是:您知道文件的位置吗? Jebby 有一个可以在目录中爬行的答案。

这是一个不使用“import os”的解决方案

dir_fullpath = "c:/project_folder/data"
dir_path = "data"
filename = "file.txt"
try:
   f = open(dir_path + "/" + filename, 'r')
#  print("open " +dir_path + "\" + filename)
#  data=[]
   for line in f:
     print (line.rstrip())
#    data.append(line.rstrip()) 
   f.close()

except IOError:
   print("Fail to open" + dir_path + "\" + filename)

【讨论】:

  • 看起来您的 dir_fullpath 与 pythonpath 或 current-working-directory 相关,并且您使用的是“相对路径概念”。你是说 dir_fullpath = 'C:\Users\Mike\AppData\Local\Programs\Python\Data'?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-13
  • 1970-01-01
  • 1970-01-01
  • 2018-04-22
  • 2010-09-12
相关资源
最近更新 更多