如何按照循环的顺序更改文件



我在一个名为0的文件夹中有25个json文件。Json到24。json,我正在尝试批量打开和重命名一个周边"图像"在每一个,目前都有一个占位符"https://"在"图像"中场。

.json当前在每个json文件中显示如下:


{"image": "https://", "attributes": [{"trait_type": "box color", "value": "blue"}, {"trait_type": "box shape", "value": "square"}]}

但应该是

{"image": "https://weburlofnewimage/0", "attributes": [{"trait_type": "box color", "value": "blue"}, {"trait_type": "box shape", "value": "square"}]}

我在像dropbox这样的网站上有一个中央文件夹,它的url结构为https://weburlofnewimage/0,/1,/2等。所以我想打开每个文件,改变图像的值键替换为"https://weburlofnewimage/+当前文件编号+ '.png'"

到目前为止,我能够遍历文件并在json文件中成功地更改图像周长,但是文件似乎以随机顺序迭代,因此在循环1上,我得到文件20,结果文件20被给定文件0的图像url。

代码如下:

import json
import os
folderPath = r'/path/FolderWithJson/'
fileNumber = 0
for filename in os.listdir(folderPath):
print('currently on file ' + str(fileNumber))
if not filename.endswith(".json"): continue
filePath = os.path.join(folderPath, filename)

with open(filePath, 'r+') as f:
data = json.load(f)
data['image'] = str('https://weburlofnewimage/' + str(fileNumber) + '.png')
print('opening file ' + str(filePath))

os.remove(filePath)
with open(filePath, 'w') as f:
json.dump(data, f, indent=4)
print('removing file ' + str(filePath))
fileNumber +=1

这导致我得到以下打印输出:

currently on file 10 (on loops 10)
currently preparing file 2.json (its working on file #2...)
opening file /path/FolderWithJson/2.json
removing file /path/FolderWithJson/2.json

然后当我看2。我看到图像被更改为"https://weburlofnewimage/10.png"而不是"https://weburlofnewimage/2.png">

从文件名中提取数字。不要用你自己的数。请记住,你永远不需要在字符串上使用str函数。许多人似乎正在养成那个坏习惯。

import json
import os
folderPath = '/path/FolderWithJson/'
for filename in os.listdir(folderPath):
if not filename.endswith(".json"): 
continue
fileNumber = os.path.splitext(filename)[0]
print('currently on file', fileNumber)
filePath = os.path.join(folderPath, filename)
print('opening file', filePath)
with open(filePath, 'r') as f:
data = json.load(f)
data['image'] = 'https://weburlofnewimage/'+fileNumber +'.png'
print('rewriting file', filePath)
with open(filePath, 'w') as f:
json.dump(data, f, indent=4)

您可以使用直接路径打开文件,而不是遍历目录。我将使用for循环将数字插入到路径中,这样它们就可以按顺序迭代。

for fileNumber in range(0,24):
with open(f'my_file/{fileNumber}.json') as f:
...doMyCode...

最新更新