如何使用子目录的数据文件并在Python中执行迭代操作

发布于 2025-01-26 14:23:51 字数 1722 浏览 2 评论 0原文

我在当前目录中有我的jupyter笔记本(Python脚本)。在当前目录中,我有两个子文件夹,即ab。在两个目录中ab我的.dat文件具有相同名称。例如,目录a包含文件,即x1-x1-val_1x1-x1-val_5x1-x1-val_11 ... x1-x1-val_86x1-x2-val_1x1-x2-val_5x1 -x2-val_11 ... x1-x2-val_86,IE值在范围内(1,90,5)。同样,我有目录中的文件b

我想使用我的python脚本访问ab中的文件,以在.dat文件上执行迭代操作。我现在的代码仅在当前目录中保存目录 a a a a b 的文件时才有效。例如,我的脚本使用以下函数。

def get_info(test):     
    my_dict = {'test':test}   
    c = []    
    
    for i in range(1,90,5):    
        x_val = 'x_val_'+test+'-val_'+str(i)
        y_val = 'y_val_'+test+'-val_'+str(i)
        
        my_dict[x_val],my_dict[y_val]= np.loadtxt(test+'-val_'+str(i)+'.dat'
                                                        ,usecols= (1,2),unpack=True)
        dw = compute_yy(my_dict[x_val],my_dict[y_val],test)
        c.append(dw)
    
    my_dict.update({test+'_c'+:np.array(c)})

    return my_dict

我调用get_info()通过使用以下方式:

tests = ['x1-x1', 'x1-x2']

new_dict = {}
for i in tests:
     new_dict.update({i:get_info(i)})

如何使用代码在Directory a和/或b中访问文件?我知道这是关于提供正确的道路,但我不确定该怎么做。我想的一种方法是遵循;

ext = '.dat'
for files in os.listdir(path_to_dir):
    if files.endswith(ext):
        print(files)   # do operations

替代方法可能是使用os.path.join()。但是,我无法解决它,因此我可以使用相同的python脚本(也许有最小的更改)可以使用文件并在子文件夹中迭代a a and b 。感谢您提前的反馈!

I have my jupyter notebook (python script) in current directory. In current directory, I have two subfolders, namely a and b. In both directories a and b I have equal number of .dat files with same names. For example, directory a contains files, namely x1-x1-val_1, x1-x1-val_5, x1-x1-val_11...x1-x1-val_86 and x1-x2-val_1, x1-x2-val_5, x1-x2-val_11...x1-x2-val_86, i.e. values are in range(1,90,5). Likewise I have files in directory b.

I want to use my python script to access files in a and b to perform iterative operations on .dat files. My present code works only if I keep files of directory a or b in current directory. For example, my script uses following function.

def get_info(test):     
    my_dict = {'test':test}   
    c = []    
    
    for i in range(1,90,5):    
        x_val = 'x_val_'+test+'-val_'+str(i)
        y_val = 'y_val_'+test+'-val_'+str(i)
        
        my_dict[x_val],my_dict[y_val]= np.loadtxt(test+'-val_'+str(i)+'.dat'
                                                        ,usecols= (1,2),unpack=True)
        dw = compute_yy(my_dict[x_val],my_dict[y_val],test)
        c.append(dw)
    
    my_dict.update({test+'_c'+:np.array(c)})

    return my_dict

I call get_info() by using following:

tests = ['x1-x1', 'x1-x2']

new_dict = {}
for i in tests:
     new_dict.update({i:get_info(i)})

How can I use my code to access files in either directory a and/or b? I know its about providing correct path, but I am unsure how can I do so. One way I thought is following;

ext = '.dat'
for files in os.listdir(path_to_dir):
    if files.endswith(ext):
        print(files)   # do operations

Alternative could be to make use of os.path.join(). However, I am unable to solve it such that I can use same python script (with minimum changes perhaps) that can use files and iterate on them which are in subfolders a and b. Thanks for your feedback in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

过气美图社 2025-02-02 14:23:51

如果要在每个文件夹sameatelly上运行get_info(),则有两种方法:

首先:由 @Medium-difimensional在评论中描述,

您可以使用os。 CHDIR(文件夹)更改当前工作目录。然后,代码将在此文件夹中使用文件运行,

中查看当前工作目录

os.chdir("a")
get_info(i)
os.chdir("..") # move back to parent folder

os.chdir("b")
get_info(i)
os.chdir("..") # move back to parent folder

您可以在print(os.getCwd()) chdir()(类似于命令cd)在控制台中)可以使用相对路径(r“ a“)完整路径(r“ c:\ full \ path \ to \ a”)和<代码> .. 移动到父文件夹(r“ a \ .. \ b”

如果文件可以在嵌套文件夹中,则可能不会回去您可以使用getcwd()

cwd = os.getcwd()

os.chdir("folder1/folder2/a")
get_info(i)
os.chdir(cwd) # move back to previous folder

os.chdir("folder1/folder2/b")
get_info(i)
os.chdir(cwd) # move back to previous folder

(btw:在Linux上的控制台您可以使用cd-移动到以前的文件夹)

second:当您打开文件时,请使用文件夹,

每个获取文件名的命令也可以使用文件夹\ filename获得路径(可以是相对路径,完整路径和..)喜欢

  • r“ a \ filename.dat”
  • r“ c:\ full \ path \ to \ b \ filename.dat”
  • r“ a \ .. \ b \ filename.dat“

因此您可以使用Extra option 文件夹定义函数

def get_info(text, folder):

,并在读取文件

loadtxt(folder + r'\' + test+'-val_'+str(i)+'.dat', ...)

或使用f-string的更读取

loadtxt(rf'{folder}\{test}-val_{i}.dat', ...)

时使用此文件夹,然后再使用此文件 夹。将其运行为

get_info(i, "a")

get_info(i, "b")

If you want to run get_info() on every folder separatelly then you have two methods:

First: described by @medium-dimensional in comment

You can use os.chdir(folder) to change Current Working Directory. And then code will run with files in this folder

You can see current working directory with print( os.getcwd() )

os.chdir("a")
get_info(i)
os.chdir("..") # move back to parent folder

os.chdir("b")
get_info(i)
os.chdir("..") # move back to parent folder

chdir() (similar to command cd in console) can use relative path (r"a") full path (r"C:\full\path\to\a") and .. to move to parent folder (r"a\..\b")

If files can be in nested folders then .. may not go back you can use getcwd()

cwd = os.getcwd()

os.chdir("folder1/folder2/a")
get_info(i)
os.chdir(cwd) # move back to previous folder

os.chdir("folder1/folder2/b")
get_info(i)
os.chdir(cwd) # move back to previous folder

(BTW: in console on Linux you can use cd - to move back to previous folder)

Second: use folder when you open file

Every command which gets filename can also get path with folder\filename (it can be relative path, full path, and path with ..) like

  • r"a\filename.dat"
  • r"C:\full\path\to\b\filename.dat"
  • r"a\..\b\filename.dat"

So you could define function with extra option folder

def get_info(text, folder):

and use this folder when you read file

loadtxt(folder + r'\' + test+'-val_'+str(i)+'.dat', ...)

or more readable with f-string

loadtxt(rf'{folder}\{test}-val_{i}.dat', ...)

And later you run it as

get_info(i, "a")

get_info(i, "b")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文