def dodajAdresArtykulu(urlArtykulu):
with open(SPIS_ARTYKULOW, 'w') as sp:
spisArtykulow = json.load(sp)
artykulIstnieje = False
for artykul in spisArtykulow:
if artykul.url == urlArtykulu:
artykulIstnieje = True
if not artykulIstnieje:
logger.debug(f"Dadaję nowy adres do bazy ({urlArtykulu})")
spisArtykulow.append(
)
else:
logger.debug(f"Adres już w bazie ({urlArtykulu})")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To append a new item to a file that stores an array of dictionaries, you should follow these steps:
Read the existing data from the file.
Modify the data in memory (e.g., append a new dictionary).
Write the updated data back to the file.
Here’s how you can implement this in your dodajAdresArtykulu function. I'll also address whether to use a constructor or raw data.
Updated Function
python
import json
import os
from datetime import datetime
# Constants
SPIS_ARTYKULOW = 'articles.json' # File to store the array of dictionaries
def dodajAdresArtykulu(urlArtykulu):
# Initialize the list if the file doesn't exist
if not os.path.exists(SPIS_ARTYKULOW):
spisArtykulow = []
else:
with open(SPIS_ARTYKULOW, 'r') as sp:
spisArtykulow = json.load(sp)
# Check if the article already exists
artykulIstnieje = any(artykul["url"] == urlArtykulu for artykul in spisArtykulow)
if not artykulIstnieje:
logger.debug(f"Dodać nowy adres do bazy ({urlArtykulu})")
# Create a new dictionary (raw data approach)
nowyArtykul = {
"url": urlArtykulu,
"index_timestamp": datetime.utcnow().isoformat() + "+00:00",
"title": "",
"text": "",
"date": "",
"tags": ""
}
spisArtykulow.append(nowyArtykul)
# Write the updated list back to the file
with open(SPIS_ARTYKULOW, 'w') as sp:
json.dump(spisArtykulow, sp, indent=4, ensure_ascii=False)
else:
logger.debug(f"Adres już w bazie ({urlArtykulu})")
Key Points
File Handling:
Use 'r' mode to read the file and 'w' mode to write (overwrites the file).
If the file doesn't exist, initialize an empty list.
Checking for Duplicates:
Use any() with a generator expression to check if the URL already exists.
Appending Raw Data:
Directly create a dictionary with the required keys and values. This is simpler than using a constructor for this use case.
Writing Back to File:
Use json.dump() with indent=4 for pretty-printing and ensure_ascii=False to handle non-ASCII characters.
Why Not Use a Constructor?
For this simple dictionary structure, using a constructor (e.g., a class) is overkill. Raw dictionaries are sufficient and more Pythonic for this purpose. However, if you later need to add methods or validation logic, you could consider using a class.
Example Class Approach (Optional)
If you decide to use a class later:
python
class Artykul:
def __init__(self, url, index_timestamp=None, title="", text="", date="", tags=""):
self.url = url
self.index_timestamp = index_timestamp or datetime.utcnow().isoformat() + "+00:00"
self.title = title
self.text = text
self.date = date
self.tags = tags
def to_dict(self):
return {
"url": self.url,
"index_timestamp": self.index_timestamp,
"title": self.title,
"text": self.text,
"date": self.date,
"tags": self.tags
}
# Usage in the function:
nowyArtykul = Artykul(urlArtykulu).to_dict()
spisArtykulow.append(nowyArtykul)
For now, the raw dictionary approach is cleaner and more efficient.