【问题标题】:writing multiple text files into arrays python将多个文本文件写入数组python
【发布时间】:2014-03-09 22:22:48
【问题描述】:

我正在尝试对数组中的值执行一些数学函数。但我想对多个文件执行此操作,因为对每个文件使用 loadtxt 很乏味。由于每个 .txt 文件包含三列,我想将 t、x、y 分配为这些列的数组。我在这方面经验不足。我使用 os.chdir 因为我将目录更改为特定文件夹中的文件,问题在于定义数组。

os.chdir(r"F:\Thermal Motion")
files = dir('*.txt')
for i in range(len(files)):
    t, x, y = loadtxt(files(i))

【问题讨论】:

    标签: arrays python-2.7 numpy dir


    【解决方案1】:

    您可以使用unpack=True parameter,将结果解压缩到单独的txy 数组中:

    from glob import glob
    import numpy as np
    
    for path in glob(r"F:\Thermal Motion\*.txt"):
        t, x, y = np.loadtxt(path, unpack=True)
        use_the_arrays_here(x, y, t) # <--  use mathematical functions here
    

    【讨论】:

    • use_the_arrays_here(x,y,t) 是做什么的,因为我收到错误,即未定义
    • @Kimi,这只是一个示例,用于展示您可以使用 xyt 在哪里做其他事情。在这里您可以“对数组中的值执行一些数学函数”。
    【解决方案2】:

    如果您的问题允许,您也可以尝试使用 csvreader 库为您完成大量工作。

    另外,如果您知道文件的路径,则实际上不需要使用chdir,只需将路径直接传递给 open 调用,或者将目录和文件名与以下内容结合起来:

    full_path = os.path.join(dir_path, filename)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 2018-08-04
      • 2022-11-17
      相关资源
      最近更新 更多