【问题标题】:How to open concurrently two files with same name and different extension in python?如何在python中同时打开两个具有相同名称和不同扩展名的文件?
【发布时间】:2016-10-17 10:25:10
【问题描述】:

我有一个包含多个文件的文件夹:

  a.txt
  a.json

  b.txt
  b.json

等等:

使用 for 循环我想同时打开几个文件(a.txt 和 a.json)。

有没有办法在python中使用'with'语句来做到这一点?

【问题讨论】:

  • 你事先知道文件名,还是从目录中读取?您能否详细说明您想要实现的目标?
  • 不太清楚你的实际问题是什么。查找文件名对?打开文件?以下是使用 with 一次打开多个文件的方法:stackoverflow.com/questions/4617034/…
  • 是的,我事先知道文件名。它们是同名但扩展名不同的一系列情侣。我必须逐个打开同名但扩展名不同的夫妇。
  • 我已经看到了上面的链接,但是它不起作用,因为我在多个文件上使用了 for 循环,而且我不能每次都写文件名。

标签: python-2.7 file io


【解决方案1】:

您可以执行以下操作,构建一个以文件名无扩展名为键的字典,并计算与所需扩展名匹配的文件数。然后你可以遍历字典打开文件对:

import os
from collections import defaultdict

EXTENSIONS = {'.json', '.txt'}

directory = '/path/to/your/files'

grouped_files = defaultdict(int)

for f in os.listdir(directory):
    name, ext = os.path.splitext(os.path.join(directory, f))
    if ext in EXTENSIONS:
        grouped_files[name] += 1

for name in grouped_files:
    if grouped_files[name] == len(EXTENSIONS):
        with open('{}.txt'.format(name)) as txt_file, \
                open('{}.json'.format(name)) as json_file:
            # process files
            print(txt_file, json_file)

【讨论】:

    【解决方案2】:

    我有两个不同文件的文件夹,一个是 .jpg,另一个是 .xml,这就是我将它们放入另一个文件夹的方式

    import os
    from pathlib import Path
    import shutil
    
    #making the list to store the name
    picList=list()
    xmlList=list()
    
    
    #making the directory path
    xmlDir = os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML')
    picDir=os.listdir('C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img')
    dest=r'C:\Users\%USERNAME%\Desktop\img+xml\i'
    
    
    #appending the file name to the list
    for a in xmlDir:
        a=Path(a).stem
        xmlList.append(a)
        picList.append(a)
    
    
    #matching and putting file name in destination
    for a in xmlList:
        for b in picList:
            if a==b:
                try:
                    shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\XML\\{a}.xml',dest)
                    shutil.move(f'C:\\Users\\%USERNAME%\\Desktop\\img+xml\\img\\{b}.jpg',dest)
                except Exception as e:
                            print(e)
           
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 2021-11-15
      • 2017-04-03
      • 1970-01-01
      相关资源
      最近更新 更多