Create new files, dont overwrite existing files, in python

2024/10/7 14:26:39

I'm writing to a file in three functions and i'm trying not overwrite the file. I want every time i run the code i generate a new filewith open("atx.csv", 'w')as output:writer = csv.writer(output)

Answer

If you want to write to different files each time you execute the script, you need to change the file names, otherwise they will be overwritten.

import os
import csvfilename = "atx"i = 0
while os.path.exists(f"{filename}{i}.csv"):i += 1with open(f"{filename}{i}.csv", 'w') as output:writer = csv.writer(output)writer.writerow([1, 2, 3]) #or whatever you want to write in the file, this line is just an example

Here I use os.path.exists() to check if a file is already present on the disk, and increment the counter.

First time you run the script, you get axt0.csv, second time axt1.csv, and so on.

Replicate this for your three files.

EDIT

Also note that here I'm using formatted string literals which are available since python3.6. If you have an earlier version of python, use "{}{:d}.csv".format(filename, i) instead of f"{filename}{i}.csv"

EDIT bis after comments

If the same file is needed to be manipulated by more functionsduring the execution of the script, the easiest thing came to my mind is to open the writer outside the functions and pass it as an argument.

filename = "atx"i = 0
while os.path.exists(f"{filename}{i}.csv"):i += 1with open(f"{filename}{i}.csv", 'w') as output:writer = csv.writer(output)foo(writer, ...) #put the arguments of your function instead of ...bar(writer, ...)etc(writer, ...)

This way each time you call one of the functions it writes to the same file, appending the output at the bottom of the file.

Of course there are other ways. You might check for the file name existence only in the first function you call, and in the others just open the file with the 'a' options, to append the output.

https://en.xdnf.cn/q/118809.html

Related Q&A

Python List comprehension execution order [duplicate]

This question already has answers here:Understanding nested list comprehension [duplicate](2 answers)Closed 4 years ago.matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] squared = [[x**2 for x in row] for row…

Subtract two strings in python

I should calculate the difference between elements two different list. This is my code :import operator a = [5, 35.1, FFD] b = [8.5, 11.3, AMM] difference = [each[0] - each[1] for each in zi…

Python assignment for a phonebook

This weeks lab is based on the example on pages 53,54 of the wikibook "Non-Programmers Tutorial For Python" by Josh Cogliati (2005), (see http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutor…

ImportError: No module named application [duplicate]

This question already has answers here:What is __init__.py for?(14 answers)Closed 6 years ago.I am running a flask application and connecting to database with Flask-mysqlAlchemy when I am running my s…

Detect keypress without drawing canvas or frame on tkinter [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 6…

regex to extract a set number of words around a matched word

I was looking around for a way to grab words around a found match, but they were much too complicated for my case. All I need is a regex statement to grab, lets say 10, words before and after a matched…

How do I make a minimal and reproducible example for neural networks?

I would like to know how to make a minimal and reproducible deep learning example for Stack Overflow. I want to make sure that people have enough information to pinpoint the exact problem with my code.…

Increase the capture and stream speed of a video using OpenCV and Python [duplicate]

This question already has answers here:OpenCV real time streaming video capture is slow. How to drop frames or get synced with real time?(4 answers)Closed 2 years ago.I need to take a video and analyz…

Getting Pyphons Tkinter to update a label with a changing variable [duplicate]

This question already has answers here:Making python/tkinter label widget update?(5 answers)Closed 8 years ago.I have a python script which I have written for a Raspberry Pi project, the script reads …

Can someone help me installing pyHook?

I have python 3.5 and I cant install pyHook. I tried every method possible. pip, open the cmd directly from the folder, downloaded almost all the pyHook versions. Still cant install it.I get this error…