【问题标题】:Iterating through a directory and assigning each file a variable to work with遍历目录并为每个文件分配一个要使用的变量
【发布时间】:2017-03-15 05:32:22
【问题描述】:

我真的是 Python 新手,所以提前感谢您提出这个可能很愚蠢的问题:

我有一个充满 LAS 文件的目录,我想为每个文件分配一个变量,以便之后我可以继续使用它们。我似乎找不到有效的答案......下面的代码由于某种原因我无法弄清楚它不起作用 - 感谢您的帮助!

%%

### Importing function packages ### NumPy, Pandas, PyPlot, OS, LASio, Sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import lasio as las


#%%
#Directory
my_dir = os.walk("C:\\Users\\L_R\\Desktop\\test\\")
my_list = []

#Creates a list with LAS files in the DIR
for i in my_dir:
    my_list.append(i)
print my_list

#Iterates through DIR and creates dataframes out of files

count=0
current_las=my_list[count]
filename = current_las

for dirname, dirs, files in my_dir:
    while count < len(my_list):      
        if filename.endswith(".LAS"):
            las_output = las.read(filename) #module reading the file
        count = count + 1
        

【问题讨论】:

    标签: directory spyder


    【解决方案1】:

    一些事情。首先,我假设您有一本字典,并且您想要提取项目并使用保存在键中的名称将它们分配给变量。那是对的吗?

    您可以加载整个目录,然后将它们保存到正确的文件中。

    如果我是正确的,此代码将允许您首先加载数据,然后将数据保存到变量中。

    D = np.load('Dict.py')
    
    for key,val in D.items():
         exec(key + '=val')
    

    【讨论】:

    • 您好,感谢您的帮助。抱歉,没有像我应该的那样准确(对此仍然很陌生)。我实际上有一个模块(LASio),它可以读取我的数据文件并将其放入数据框中——这很好用。但是,我无法打开目录中的所有文件(.LAS 文件)以对所有 LAS 文件运行算法。
    猜你喜欢
    • 1970-01-01
    • 2011-01-31
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多