[英]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.我有下面的代码,它将我的标准化
.txt
文件完美地转换为 JSON 文件。 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.唯一的问题是,有时我有超过 300 个文件并手动执行此操作(即更改文件末尾的数字并运行脚本太多且耗时太长。我想自动执行此操作。如您所见的文件驻留在一个
folder/directory and I am placing the JSON file in a different
文件夹/目录中,但基本上保持命名约定标准化,除了以.txt
结尾而不是以 .json 结尾,但前缀或文件名相同且标准化. 一个例子是: CRAZY_CAT_FINAL1.TXT, CRAZY_CAT_FINAL2.TXT
等等一直到文件 300。我怎样才能自动化并保持文件命名约定到位,并读取 output 文件到不同的文件夹/目录? 我试过了,但似乎无法让它迭代。任何帮助将不胜感激。
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
?使用
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') )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.