The error “_csv.Error: iterator should return strings, not bytes…” indicates that you’re trying to open a CSV file in binary mode (‘rb’) instead of text mode. CSV files are inherently text-based, so Python’s CSV library expects to work with strings.
Fixing the Code
- Open the File in Text Mode: Change the way you open your CSV file:
reader = csv.reader(open("indiaafterindependence-output.csv", "r"))
The “r” stands for “read” (text mode).
Additional Enhancements
- Encoding: To avoid issues with special characters, explicitly specify the encoding of your CSV file (often UTF-8):
reader = csv.reader(open("indiaafterindependence-output.csv", "r", encoding='utf-8'))
- Error Handling: Consider adding error handling to gracefully address potential issues during CSV reading or WordPress communication:
try: reader = csv.reader(open("indiaafterindependence-output.csv", "r", encoding='utf-8')) for row in reader: insert_wp_post(row[1], row[2]) except csv.Error as e: print(f"Error reading CSV file: {e}") except xmlrpclib.Fault as e: print(f"Error communicating with WordPress: {e}")
Complete Modified Code
import datetime, xmlrpc.client as xmlrpclib, csv
# ... (Your WordPress connection details) ...
def insert_wp_post(title="Title was not passed !", content="Content was not passed !"):
# ..... (rest of your function) .....
try:
reader = csv.reader(open("indiaafterindependence-output.csv", "r", encoding='utf-8'))
for row in reader:
insert_wp_post(row[1], row[2])
except csv.Error as e:
print(f"Error reading CSV file: {e}")
except xmlrpclib.Fault as e:
print(f"Error communicating with WordPress: {e}")
Let me know if you’d like further adjustments or have any other parts of the code you want to optimize!