【问题标题】:Exporting multiple files with different filenames导出具有不同文件名的多个文件
【发布时间】:2017-06-04 20:59:06
【问题描述】:

假设我的目录中有n 文件,文件名:file_1.txt, file_2.txt, file_3.txt .....file_n.txt。我想将它们单独导入Python,然后对它们进行一些计算,然后将结果存储到n对应的输出文件中:file_1_o.txt, file_2_o.txt, ....file_n_o.txt.

我已经弄清楚如何导入多个文件:

import glob
import numpy as np

path = r'home\...\CurrentDirectory'
allFiles = glob.glob(path + '/*.txt')
for file in allFiles:
    # do something to file
    ...
    ...
    np.savetxt(file, ) ???

不太清楚如何在文件名后面附加_o.txt(或任何字符串),以便输出文件为file_1_o.txt

【问题讨论】:

    标签: python import export filenames


    【解决方案1】:

    你可以使用下面的 sn-p 来构建输出文件名吗?

    parts = in_filename.split(".")
    out_filename = parts[0] + "_o." + parts[1]  
    

    我假设 in_filename 的格式为“file_1.txt”。
    当然,将"_o."(扩展名之前的后缀)放在一个变量中可能会更好,这样您就可以在一个地方随意更改,并且可以更轻松地更改该后缀。 在你的情况下,这意味着

    import glob
    import numpy as np
    
    path = r'home\...\CurrentDirectory'
    allFiles = glob.glob(path + '/*.txt')
    for file in allFiles:
        # do something to file
        ...
        parts = file.split(".")
        out_filename = parts[0] + "_o." + parts[1]
        np.savetxt(out_filename, ) ???  
    

    但您需要小心,因为可能在将 out_filename 传递给 np.savetxt 之前,您需要构建完整路径,因此您可能需要类似
    np.savetxt(os.path.join(path, out_filename), )
    或类似的东西。
    如果您想将更改基本上组合在一行中并像我之前提到的那样定义“变量中的后缀”,您可以拥有类似

    hh = "_o." # variable suffix
    ..........
    # inside your loop now
    for file in allFiles:
        out_filename = hh.join(file.split("."))
    

    正如@NathanAck 在他的回答中提到的那样,它通过在拆分列表上使用 join 来使用另一种方式来做同样的事情。

    【讨论】:

      【解决方案2】:
      import os
      
      #put the path to the files here
      filePath = "C:/stack/codes/"
      theFiles = os.listdir(filePath)
      
      for file in theFiles:
          #add path name before the file
          file = filePath + str(file)
      
          fileToRead = open(file, 'r')
          fileData = fileToRead.read()
      
          #DO WORK ON SPECIFIC FILE HERE
          #access the file through the fileData variable
          fileData = fileData + "\nAdd text or do some other operations"
      
          #change the file name to add _o
          fileVar = file.split(".")
          newFileName = "_o.".join(fileVar)
      
          #write the file with _o added from the modified data in fileVar
          fileToWrite = open(newFileName, 'w')
          fileToWrite.write(fileData)
      
          #close open files
          fileToWrite.close()
          fileToRead.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-19
        • 1970-01-01
        • 2016-07-22
        • 2021-07-23
        相关资源
        最近更新 更多