简体   繁体   中英

How do I fix my code so that it is automated?

I have the below code that takes my standardized .txt file and converts it into a JSON file perfectly. The only problem is that sometimes I have over 300 files and doing this manually (ie changing the number at the end of the file and running the script is too much and takes too long. I want to automate this. The files as you can see reside in one folder/directory and I am placing the JSON file in a different folder/directory, but essentially keeping the naming convention standardized except instead of ending with .txt it ends with.json but the prefix or file names are the same and standardized. An example would be: CRAZY_CAT_FINAL1.TXT, CRAZY_CAT_FINAL2.TXT and so on and so forth all the way to file 300. How can I automate and keep the file naming convention in place, and read and output the files to different folders/directories? I have tried, but can't seem to get this to iterate. Any help would be greatly appreciated.

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)

Use 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')
import time
from glob import glob
import csv
import json
import os

INPATH r'C:\Users\...\...\...\Dog'
OUTPATH = r'C:\Users\...\...\...\Rat'
for csvname in glob(INPATH+'\*.txt'):
    jsonname = OUTPATH + '/' + os.basename(csvname[:-3] + 'json')
    reader = csv.DictReader(open(csvname,'r'))
    json.dump( list(reader), open(jsonname,'w') )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM