I am running Python 3.13.9 and have a script that creates a temp file, reads data from a database and outputs it as CSV in to said temp file and then sends that file to a server. I am trying to then delete the temp file when it is done.
logging.info(f"Updating list {list["name"]} using session token {token}.")
# Create a temporary CSV file
with tempfile.NamedTemporaryFile(mode="w+", newline="", suffix=".csv", delete=False) as temp_file:
temp_path = temp_file.name
logging.info(f"Using temp file {temp_file.name}.")
# Connect to SQL Server
conn_str = (
f"DRIVER={{{DRIVER}}};"
f"SERVER={list["server"]};"
f"DATABASE={list["database"]};"
"Trusted_Connection=yes;"
"TrustServerCertificate=yes;"
)
logging.info(f"Connecting to SQL Server {conn_str}.")
with pyodbc.connect(conn_str) as conn:
cursor = conn.cursor()
logging.info(f"Executing query '{list["query"]}'.")
cursor.execute(list["query"])
logging.info(f"Writing column headers.")
column_names = [column[0] for column in cursor.description]
writer = csv.writer(temp_file)
writer.writerow(column_names)
logging.info(f"Writing data lines.")
for row in cursor:
writer.writerow(row)
payload={}
files=[('file',(temp_file.name,open(temp_file.name,'rb'),'text/csv'))]
headers = {'X-Gatekeeper-SessionToken': token,'FastField-API-Key': APIKEY}
logging.info(f"Sending list csv file to {list["url"]} using token {token}.")
response = requests.request("PUT", list["url"], headers=headers, data=payload, files=files)
logging.info(f"Received response {response.text}.")
return response.text
# Remove the temp file created above
os.remove(temp_path)
This always gives me the error "PermissionError: [WinError 32] The process cannot access the file because it is being used by another process" at the os.remove line. I have tried manually closing the file first and get the same error. I have tried setting delete=True but then I get a permission error. How do I delete this file once I'm done with it?
returnsuggests this is inside a function, but it isn't. Is the code incomplete?os.remove()will not be executed in the code as shown due to the precedingreturn. Also, it looks like you may have a variable (a dictionary) namedlistwhich seems a bit odd