首页 > 解决方案 > 如何修复我的代码以使其自动化?

问题描述

我有下面的代码,它将我的标准化.txt文件完美地转换为 JSON 文件。唯一的问题是,有时我有超过 300 个文件并手动执行此操作(即更改文件末尾的数字并运行脚本太多且耗时太长。我想自动执行此操作。如您所见的文件驻留在一个folder/directory and I am placing the JSON file in a different文件夹/目录中,但基本上保持命名约定标准化,除了.txt以 .json 结尾,但前缀或文件名相同且标准化。一个例子是:CRAZY_CAT_FINAL1.TXT, CRAZY_CAT_FINAL2.TXT依此类推,一直到文件 300。如何自动化并保持文件命名约定到位,并将文件读取并输出到不同的文件夹/目录?我已经尝试过,但似乎无法让它迭代。任何帮助将不胜感激。

import glob
import time
from glob import glob
import pandas as pd
import numpy as np
import csv
import json

    csvfile = open(r'C:\Users\...\...\...\Dog\CRAZY_CAT_FINAL1.txt', 'r')
    jsonfile = open(r'C:\Users\...\...\...\Rat\CRAZY_CAT_FINAL1.json', 'w')
    
    reader = csv.DictReader(csvfile)
    out = json.dumps([row for row in reader])
    jsonfile.write(out)

****************************************************************************
I also have this code using the python library "requests". How do I make this code so that it uploads multiple json files with a standard naming convention? The files end with a number...

    import requests

#function to post to api

    def postData(xactData):
        url = 'http link'
        headers = {
           'Content-Type': 'application/json',
           'Content-Length': str(len(xactData)),
           'Request-Timeout': '60000'
        }
        return requests.post(url, headers=headers, data=xactData)

    #read data
    f = (r'filepath/file/file.json', 'r')
    data = f.read()
    print(data)

    # post data
    result = postData(data)
    print(result)

标签: pythonjsonpython-3.xloopsrecursion

解决方案


使用f-strings

for i in range(1,301):
    csvfile = open(f'C:\Users\...\...\...\Dog\CRAZY_CAT_FINAL{i}.txt', 'r')
    jsonfile = open(f'C:\Users\...\...\...\Rat\CRAZY_CAT_FINAL{i}.json', 'w')

推荐阅读