python - 如何修复我的代码以使其自动化?
问题描述
我有下面的代码,它将我的标准化.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)
解决方案
使用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')
推荐阅读
- c# - IRepository 和工作单元与急切加载
- c# - 将对象相互注入
- javascript - Chart.js 在单个 x 轴上垂直对齐的点
- google-cloud-platform - Google Cloud Composer 和 Google Cloud SQL 代理
- usb - 通过USB连接STM32F7和SIM7600
- kubernetes - 如何允许 Kubernetes 作业访问主机上的文件
- php - 更新/放置路线 - 不允许的方法
- c - 试图将元素附加到多维数组。尝试运行应用程序时抛出异常
- amazon-web-services - 如何找到亚马逊 MWS wsdl
- javascript - Google Chrome 中的 IndexedDB-Bug