【问题标题】:How to create empty files in folder with names and extension from list in file Linux / Python如何在文件Linux / Python中的列表中创建具有名称和扩展名的文件夹中的空文件
【发布时间】:2021-12-09 05:19:25
【问题描述】:

我在单个文件record.txt 中有一个文件名列表,格式如下:

/home/user/working/united.txt
/home/user/working/temporary.txt
/home/user/working/fruits.txt

我在另一个文件夹中只有一个 json 格式的 temporary.txt 文件,例如 temporary.json,我需要它作为 json

我想创建不在文件夹中但存在于列表record.txt 中的所有剩余文件,以便所有丢失的文件也作为空白文件存在,最后我拥有所有三个文件。 temporary.json 有数据所以我不能新生成所有文件。只是文件夹中缺少并出现在列表中的文件。 最后,我想通过python或shell脚本得到如下所示。

united.json 
temporary.json
fruits.json

temporary.json 仍有数据

【问题讨论】:

  • attempt 在哪里?另请注意,通常在此处发布问题时,代码比文本更有价值。例如,您用 python 和 pandas 标记了问题,但我没有看到实际帖子中使用的任何内容。
  • 有几个任务,但这里没有问题或疑问。请收下tour 并阅读How to Ask

标签: python json pandas bash


【解决方案1】:

此命令“创建”文件而不删除现有文件:

while read i ; do touch "${i%.*}.json"; done<record.txt

temporary.json的修改时间会变为当前的

【讨论】:

    【解决方案2】:

    在 Python 中,您可以使用os.path.isfile 检查文件是否存在,然后使用open(filename,'w') 创建:

    from os.path import isfile
    _createTxtFlag = True
    _createJSONFlag = True
    
    
    with open('temporary.txt') as fil:
        for l in fil.readlines():
            l = l.rstrip() #to remove end of line
            #create .txt files if not exists
            if _createTxtFlag:
                if not isfile(l):
                    with open(l,'w') as newFil:
                        pass
            if _createJSONFlag:
                json_name = f"{l.split('.')[0]}.json"
                if not isfile(json_name):
                    with open(json_name,'w'):
                        pass
    

    【讨论】:

      猜你喜欢
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 2018-01-29
      • 2014-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多