f



How to create new python file with increament number, if doesn't exist?

hi,
   I want to create a new python file like 'data0.0.5', but if it is alread=
y exist then it should create 'data0.0.6', if it's also exist then next lik=
e 'data0.0.7'. I have done, but with range, please give me suggestion so th=
at I can do it with specifying range.
I was trying this way and it's working also..

     i =3D 0
    for i in range(100):
        try:
            with open('Data%d.%d.%d.json'%(0,0,i,)): pass
            continue
        except IOError:
            edxCorrectDataFile =3D file('Data%d.%d.%d.json'%(0,0,i,), 'a+')
            break

But here I have defined range 100, Is it possible without range it create m=
any required files?

Thanks
0
5/27/2013 9:27:59 AM
comp.lang.python 77058 articles. 6 followers. Post Follow

3 Replies
527 Views

Similar Articles

[PageSpeed] 26

On Mon, 27 May 2013 02:27:59 -0700, Avnesh Shakya wrote:

> I want to create a new python file like 'data0.0.5', but if it is
> already exist then it should create 'data0.0.6', if it's also exist
> then next like 'data0.0.7'. I have done, but with range, please give
> me suggestion so that I can do it with specifying range.

Try and put your description into the sequence of instructions you want 
the computer follow.

For this problem, my sequence of instructions would be:

1) Find the highest numbered existing file that matches the filename 
data0.0.[number]

2) Create a new file that is one number higher.

Now the solution is easy. Find the list of filenames in the directory 
that match a suitable regular expression, take the numeric value of a 
substring of the filename for each file and find the highest, add one to 
it, then create the new file name.

Something like the following (untested) with the relevant imports etc:

nfn="data0.0."+str(max([int(f[8:])for f in os.listdir(p)if re.match
('^data0.0.[0-9]+$',f)])+1)

-- 
Denis McMahon, denismfmcmahon@gmail.com
0
5/27/2013 10:49:00 AM
--e89a8f83a2436112f004ddb10e13
Content-Type: text/plain; charset=ISO-8859-1

Thanks


On Mon, May 27, 2013 at 4:19 PM, Denis McMahon <denismfmcmahon@gmail.com>wrote:

> On Mon, 27 May 2013 02:27:59 -0700, Avnesh Shakya wrote:
>
> > I want to create a new python file like 'data0.0.5', but if it is
> > already exist then it should create 'data0.0.6', if it's also exist
> > then next like 'data0.0.7'. I have done, but with range, please give
> > me suggestion so that I can do it with specifying range.
>
> Try and put your description into the sequence of instructions you want
> the computer follow.
>
> For this problem, my sequence of instructions would be:
>
> 1) Find the highest numbered existing file that matches the filename
> data0.0.[number]
>
> 2) Create a new file that is one number higher.
>
> Now the solution is easy. Find the list of filenames in the directory
> that match a suitable regular expression, take the numeric value of a
> substring of the filename for each file and find the highest, add one to
> it, then create the new file name.
>
> Something like the following (untested) with the relevant imports etc:
>
> nfn="data0.0."+str(max([int(f[8:])for f in os.listdir(p)if re.match
> ('^data0.0.[0-9]+$',f)])+1)
>
> --
> Denis McMahon, denismfmcmahon@gmail.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>

--e89a8f83a2436112f004ddb10e13
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: quoted-printable

<div dir=3D"ltr">Thanks<br></div><div class=3D"gmail_extra"><br><br><div cl=
ass=3D"gmail_quote">On Mon, May 27, 2013 at 4:19 PM, Denis McMahon <span di=
r=3D"ltr">&lt;<a href=3D"mailto:denismfmcmahon@gmail.com" target=3D"_blank"=
>denismfmcmahon@gmail.com</a>&gt;</span> wrote:<br>
<blockquote class=3D"gmail_quote" style=3D"margin:0 0 0 .8ex;border-left:1p=
x #ccc solid;padding-left:1ex"><div class=3D"im">On Mon, 27 May 2013 02:27:=
59 -0700, Avnesh Shakya wrote:<br>
<br>
&gt; I want to create a new python file like &#39;data0.0.5&#39;, but if it=
 is<br>
&gt; already exist then it should create &#39;data0.0.6&#39;, if it&#39;s a=
lso exist<br>
&gt; then next like &#39;data0.0.7&#39;. I have done, but with range, pleas=
e give<br>
&gt; me suggestion so that I can do it with specifying range.<br>
<br>
</div>Try and put your description into the sequence of instructions you wa=
nt<br>
the computer follow.<br>
<br>
For this problem, my sequence of instructions would be:<br>
<br>
1) Find the highest numbered existing file that matches the filename<br>
data0.0.[number]<br>
<br>
2) Create a new file that is one number higher.<br>
<br>
Now the solution is easy. Find the list of filenames in the directory<br>
that match a suitable regular expression, take the numeric value of a<br>
substring of the filename for each file and find the highest, add one to<br=
>
it, then create the new file name.<br>
<br>
Something like the following (untested) with the relevant imports etc:<br>
<br>
nfn=3D&quot;data0.0.&quot;+str(max([int(f[8:])for f in os.listdir(p)if re.m=
atch<br>
(&#39;^data0.0.[0-9]+$&#39;,f)])+1)<br>
<span class=3D"HOEnZb"><font color=3D"#888888"><br>
--<br>
Denis McMahon, <a href=3D"mailto:denismfmcmahon@gmail.com">denismfmcmahon@g=
mail.com</a><br>
--<br>
<a href=3D"http://mail.python.org/mailman/listinfo/python-list" target=3D"_=
blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></span></blockquote></div><br></div>

--e89a8f83a2436112f004ddb10e13--
0
5/27/2013 11:00:26 AM
Avnesh Shakya <avnesh.nitk@gmail.com> wrote:
>    I want to create a new python file like 'data0.0.5', but if it is already
> exist then it should create 'data0.0.6', if it's also exist then next like
> 'data0.0.7'. I have done, but with range, please give me suggestion so that
> I can do it with specifying range.
> I was trying this way and it's working also..

>     i = 0
>     for i in range(100):
>         try:
>             with open('Data%d.%d.%d.json'%(0,0,i,)): pass
>             continue
>         except IOError:
>             edxCorrectDataFile = file('Data%d.%d.%d.json'%(0,0,i,), 'a+')
>             break

> But here I have defined range 100, Is it possible without range it create
> many required files?

What about something as simple as this?

  i = 0
  while os.path.exists( 'Data{0}.{1}.{2}.json'.format( 0, 0, i ) ) :
      i += 1
  f = open( 'Data{0}.{1}.{2}.json'.format( 0, 0, i ), 'w' )

For your code you'ld make it e.g.

  i = 0
  try:
      while True :
          with open('Data%d.%d.%d.json'%(0,0,i)):
              i += 1
  except IOError:
      edxCorrectDataFile = file('Data%d.%d.%d.json'%(0,0,i), 'a+')

Note that I don't see how all this trying to open a file and
catching an exeception if it doesn't exist is any better
than simply using os.path.exists(). You may have read some-
where that it avoids a race condition and would thus be more
secure. That's not the case here, an attacker still could
create e.g. a symbolic link with the name of the file you're
going to open between the time the exception is thrown and your
program getting around to open the file you expect not to exist,
so nothing is gained by using this somewhat convoluted method.
What would be needed for avoiding a race condition is an addi-
tional flag to be passed to open() like the for example the
O_EXCL flag that can be passed to Unix' open() system function.
But that isn't supported by Pythons open() function which
rather likeky is based on C's fopen() function). The best
advice to avoid such problems is probably not to open files
with a predictable name (or better to use one of the methods
to create files with names guaranteed to be unique by the
system) in directories to which other users than you also
have write permission.
                            Regards, Jens
-- 
  \   Jens Thoms Toerring  ___      jt@toerring.de
   \__________________________      http://toerring.de
0
jt68 (1149)
5/27/2013 11:13:19 AM
Reply:

Similar Artilces:

How to determine whether a file doesn't exist or doesn't have enough permissions
Hello everone, I am stuck in determining whether a file does not exist or does not have enough permissions so that access to this file is denied?". I am using java.io.File.exists() or java.io.File.canRead() methods to check this but both of them just return false in both above mentioned cases. In the documentation however its mentioned that these method throw SecurityException - If a security manager exists and its SecurityManager.checkRead(java.lang.String) method denies read access to the file. But then problem is to write a security manager which denies read access if the file does not...

open file in c / create if file doesn't exist
Hi everyone! I have a problem with trying to open a file in C. The following line in my code is suppoed to open a specified file if it exists and create a new one with this name if one doesn't exist: if ((shfd = open(argv[2], O_CREAT | O_RDWR, 0644)) < 0) my_error("open failed"); If I try to open a file that doesn't exist I get an error: Bus error And when it creates a file it sets permissions to -rw------ instead of -rw-r--r-- as I would hope... Is there something I'm not getting about how O_CREATE works?... However, if I try to open existing file that is no...

Why doesn't Python's "robotparser" like Wikipedia's "robots.txt" file?
For some reason, Python's parser for "robots.txt" files doesn't like Wikipedia's "robots.txt" file: >>> import robotparser >>> url = 'http://wikipedia.org/robots.txt' >>> chk = robotparser.RobotFileParser() >>> chk.set_url(url) >>> chk.read() >>> testurl = 'http://wikipedia.org' >>> chk.can_fetch('Mozilla', testurl) False >>> The Wikipedia robots.txt file passes robots.txt validation, and it doesn't disallow unknown browsers. But the Python pars...

python doesn't like my numbers
hi, is there any way to convince python not to take my (phone)numbers starting with zero as octals? >>> int(088) File "<stdin>", line 1 int(088) ^ SyntaxError: invalid token thanks Paul paul k schreef: > hi, > > is there any way to convince python not to take my (phone)numbers > starting with zero as octals? > > >>> int(088) > File "<stdin>", line 1 > int(088) > ^ > SyntaxError: invalid token What is the integer value of a phone number? -- Peter Kleiweg L:NL,af,...

Creating a file that doesn't exist
Hello, I was wondering if it is possible to create a file if it doean't exist. I am using fstream and writing in and out a binary file. I check to see if the file is opened. if it doesn't get opened, i want to create the file. I was wondering if this can be done. This is the code i have for opening the file: fstream rfile("names.db", ios::binary| ios::in | ios::out); if ( !rfile ) { cerr << "Could not open file 'names.db'\n"; } I am hoping to put the creating of the file after the cerr. i hope someone can help me out with this. thanks. ...

Python doesn't see the directories I create
When I create a subfolder, python is not seeing it. Can someone please explain this behaviour ? I just started with python, read the tutorial over the weekend and am writing my very first script. So I may not be seeing something. Both os.path and glob.glob seem not to see a folder I created. Other sibling folders seem to work fine. On a whim I tried paths with \\ double slashes and that worked. But why should single slashes work for some folders and not for others ?? What I need is to match a bunch of files in a folder with glob.glob(C:\enhancement\rawfiles\*.bin.gz) and send them to a...

Strange behavior: file doesn't exist error even if the file does exist
I am doing the following simple loop: I have (.pgm) images with names range from 0:1000, I am loading the images (using imread) on one-by-one basis using for-loop, I do some manipulation then save them back. Everything is okay for the first 491 images; afterwards matlab gives me the error &#8220; File does not exist&#8221; Well the file &#8220;does&#8221; exist. Also now if let&#8217;s say I try to &#8220;imread&#8221;some previously read files for example file number 490 or even file number 1, which the code already read ithem and did the manipulation. It ...

Doesn't MS-Windows likes Python ? (or: why more than 20 sec delay when running a program from Python)
hello, I've an AutoIt program that set some switches in the LAN settings. When I launch the AutoIt executable, the settings are changed immediately. When I launch the AutoIt executable from python (which is the intention), it hangs for about 20 seconds, before any action appears on the screen. Analyzing the script, shows that it hangs on the next 2 lines: Run ( "control.exe ncpa.cpl" ) WinWait( "Network Connections") Transfering the Run command to Python, it hangs on the next subprocess call subprocess.call ( [ r"control.exe", "ncpa.cpl&quo...

python logging config file doesn't allow filters?
The python logging module is a beautiful masterpiece. I'm studying filters and the config-file approach. Is it possible to define a filter somehow and then refer to it in my config file? TIA Matt On 26 Oct, 17:23, Matthew Wilson <m...@tplus1.com> wrote: > I'm studying > filters and the config-file approach. Is it possible to define a filter > somehow and then refer to it in my config file? I'm afraid not. There's currently no support for filters in the configuration file format, and no plans to include them in the near future (your post is the first time c...

Urgent! C++ ESQL, db connection doesn't exist when it is used by a thread which didn't create it.
I have written an ESQL application using C++. This program has a main thread, which will create a "client thread" and a database connection with an unique connection name when it receives a client connection. i.e. One dedicated database connection for one thread. The thread will handle some requests from a client and perform some databse operations using the dedicated database connection. My aplication can receive many client connections. However, i got the same error every time I execute the sql, say, execute immediate. The error is sqlcode = -33620271 sqlerrmc is "cs_objects: cslib user api layer: external error: 08003 connection exception -- connection does not exist" I think the connection/ sqlca are somehow binded to the information of the thread which creates them and can only be used by the thread. Therefore my program doesn't work because the connection is created by a main thread, but it is used by a "client thread". I have two experiment 1) After the connection is established, i use execute immediate to update a record in the database and it works! And so i come up with this conclusion. 2) If i don't use threads, everything works. I have used the -r precompiler option but it doesn't help. In fact, my application also needs to support dynamic sql method 4 and i wonder if it more problems will arise. Could anyone please give me some hints to solve this problem? Hello, General rules for using ESQL w...

File exists but Python says 'not found'.
I'm running this code that reads 2 csv files (one of them is train.csv). The code gives an error saying 'file not does not exist'. However, the file does exists in the same location as the .py file. Can someone please help me on this. Thanks! Code Output--> Reading dataset... Traceback (most recent call last): File "c:\Project_1\regression_2.py", line 163, in <module> main(**args) File "c:\Project_1\regression_2.py", line 80, in main train_data = pd.read_csv(train) File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 401, in parser _f return _read(filepath_or_buffer, kwds) File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 209, in _read parser = TextFileReader(filepath_or_buffer, **kwds) File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 509, in __init __ self._make_engine(self.engine) File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 611, in _make_ engine self._engine = CParserWrapper(self.f, **self.options) File "c:\Python27\lib\site-packages\pandas\io\parsers.py", line 893, in __init __ self._reader = _parser.TextReader(src, **kwds) File "parser.pyx", line 312, in pandas._parser.TextReader.__cinit__ (pandas\sr c\parser.c:2846) File "parser.pyx", line 512, in pandas._parser.TextReader._setup_parser_source (pandas\src\parser.c:4893) IOError...

Why Doesn't Labview Place New Indicators I create near existing ones on the block diagram?
When I create a new indicator from the block diagram side Labview usually places them way off in space on the front panel instead of near my other existing stuff. I then have to go find them and drag them back to where I can see them using labview's slow border autoscrolling. This is extremely annoying. I would think that after all the revisions of labview with all the intellegent app engineers NI has that something this simple would have been fixed a while ago. Is there a setting I don't know about or something? Doesn't everyone else have the same annoying problem? Help. If you c...

How can I creat a file if the file doesn't exit?
int main( ) { string str; string filename; fstream outfile; cout<<"Input the file name you will save in:"<<endl; getline(cin,filename); outfile.open(filename.c_str() ); //cin.clear(); //清空流 cout<<"Please input your text....."<<endl; getline(cin,str); outfile<<str; outfile.close(); return 0; } when it request me to input the filename, if the filename I input is exit, the program work normally. But if the file doesn't exit, it can't work . how can i creat a new file when it doesn't exit? Thanks~ ^_^# { Ple...

Installation on Mac OSX 10.6.8 doesn't create the folder: /System/Library/Frameworks/Python.framework/Versions/2.7/
Hello people, I installed python 2.7 on Mac OSX 10.6.8 with no problems and it is working fine. When I try to install Kivy however (www.kivy.org), I get an error saying: /usr/local/bin/kivy: line 24: /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7: No such file or directory /usr/local/bin/kivy: line 24: exec: /System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7: cannot execute: No such file or directory Upon inspection the there are folders named 2.3, 2.5 and 2.6 in the Versions folder, but indeed no folder named "2.7". When I log...

create new python file
Hi, Can anyone please tell me how to dynamically create a new python file within a program??? --047d7bdc13ce6fe6dd04de566e4a Content-Type: text/plain; charset=ISO-8859-1 On 4 Jun 2013 17:14, <kakararunachalservice@gmail.com> wrote: > > Hi, > Can anyone please tell me how to dynamically create a new python file within a program??? That's generally a bad idea. Why are you doing that? That said, it's just like writing to a text file. So if you write python in a text file, you're good. --047d7bdc13ce6fe6dd04de566e4a Content-Type: text/html; charset=ISO-8859-1 <p dir="ltr"><br> On 4 Jun 2013 17:14, &lt;<a href="mailto:kakararunachalservice@gmail.com">kakararunachalservice@gmail.com</a>&gt; wrote:<br> &gt;<br> &gt; Hi,<br> &gt; Can anyone please tell me how to dynamically create a new python file within a program???</p> <p dir="ltr">That&#39;s generally a bad idea. Why are you doing that?</p> <p dir="ltr">That said, it&#39;s just like writing to a text file. So if you write python in a text file, you&#39;re good.</p> --047d7bdc13ce6fe6dd04de566e4a-- On 06/04/2013 09:07 AM, kakararunachalservice@gmail.com wrote: > Hi, > Can anyone please tell me how to dynamically create a new python file within a program??? What do you mean by a "python file"? If you mean ...

Can't Open Any Files or Create New Files with Photoshop CS
I am running Windows XP Media Center 2005 Edition with 2.0 GB RAM, a 2.2 GHz CPU and Photoshop CS. Photoshop will open just fine, but when I go to File --> Open and select any type of file, nothing happens. The same thing if I try to create a new file. If I restart my computer or reinstall Photoshop it *might* work for a while, but eventually stops working again. I have tried deleting/restoring prefs, reinstalling Photoshop, reallocating RAM, but nothing seems to work. Files open fine in ImageReady and can then be transferred to Photoshop to view. I cannot find a solution to this proble...

Creating object in function doesn't seem to create a new object.
Hi folks, I'll start off with the code I wrote... (ActivePython 2.4 on Windows XP SP2) ------------------------------- class FlightCondition(object): lsf = [0,'Low Speed Flare'] vto = [0,'Vertical Take-Off'] def get_flight_condition(flight_data): fc1 = FlightCondition() for row in flight_data: fc1.lsf[0] += 1 fc1.vto[0] += 1 print 'in function get_flight_condition' print fc1.lsf print fc1.vto return fc1 for count in range(3): fc = get_flight_condition([1,2,3]) print 'returned fc' print ...

'Adding new data file' vs 'extending existing data file size' to increase Tablespace
As the Tablespace is almost filled on the running system now, we have to add additional space to the Tablespace. As I understand, the following are the two options available to do that: 1) Add a new data file to hold the additional data in Tablespace: SQL> alter tablespace my_TS add datafile '/someDir/my_TS2.dbf' size 100M; 2) Resize the existing Tablespace's data file. SQL> alter database datafile '/someDir/my_TS1.dbf' resize 200M; What is the best way to go? In my understanding, the 1st option is not preferable as the Tablespace is spread over 2 data files and ...

Why doesn't python's list append() method return the list itself?
Why doesn't python's list append() method return the list itself? For that matter, even the reverse() and sort() methods? I found this link (http://code.google.com/edu/languages/google-python- class/lists.html) which suggests that this is done to make sure that the programmer understands that the list is being modified in place, but that rules out constructs like: ([1,2,3,4].reverse()+[[]]).reverse() I want to prepend an empty list to [1,2,3,4]. This is just a toy example, since I can always do that with [[]]+[1,2,3,4]. Regards, -Dhruv. On 07/11/2010 05:59 PM, dhruvbird w...

pthread_create() doesn't start a new thread sometimes but doesn't return non-zero value on return.
I'm implementing TCP, and using a thread to be used as a timer, since I want to still be receiving and sending messages. The timer thread is used to re-transmit sends that get time-outed.. For example, i have a mutex_t object to hide a global variable that tells me if the current send has been received in the main thread or not. If after the timeout, the send has not been received, it calls the method again, which will re-transmit and start another time for that send, ibid et al. However, I issue the timeout() (my own function) to the pthread_create() and have a simple printf(), but on some creation of threads, it never gets executed. DOes this mean that the thread never gets executed? I check the return value, and it is zero. So, I'm assuming it gets created successfully, but just not executed any time soon. I waiting for 5 minutes one time, but still the thread didn't get executed. void *timeout( void *a ) { ... printf("IN HERE\n"); ... } Could someone give me a clue why they think this is happening? boo wrote: > I'm implementing TCP, and using a thread to be used as a timer, since I > want to still be receiving and sending messages. The timer thread is > used to re-transmit sends that get time-outed.. > > For example, i have a mutex_t object to hide a global variable that > tells me if the current send has been received in the main thread or > not. ...

Python doesn't have one of these
http://geonames.usgs.gov/pls/gnis/MapServer?f_name=Ruby%20Canyon%20Debris%20Basin&f_state=CA&f_latlong=340952N1175952W&server=TIGER Steve I hate to be the bearer of bad news, but... http://www.jeffothy.com/australia/gallery/desert/Picture_044 ...

python doesn't install
WinXP...32 bits...professional I keep getting message note also that there is no place on the install box to start...you just click somewhere, and the install started. ...

a new Python Podcast series (and the use of Python in creating podcasting tools)
Python411 is a series of podcasts about Python, aimed at hobbyists and others who are learning Python. Each episode focuses on one aspect of learning Python, or one kind of Python programming, and points to online tools and tutorials. Python related news and events will also be reported upon. This podcast series will probably not be of much interest to expert or professional programmers. I am a hobbyist and am not qualified nor capable of creating a podcast series for accomplished programmers. Maybe someone else will do that. The four podcasts so far are titled as such: Introduction to Pyth...

Python doesn't understand %userprofile%
In xp when I try os.path.getmtime("%userprofile/dir/file%") Python bites back with "cannot find the path specified" Since my script has to run on machines where the username is unspecified I need a fix. Thanks in advance. On Jun 10, 8:56 am, bsag...@gmail.com wrote: > In xp when I try os.path.getmtime("%userprofile/dir/file%") Python > bites back with "cannot find the path specified" Since my script has > to run on machines where the username is unspecified I need a fix. > Thanks in advance. oops that should be os.path.getmtime("%userp...

Web resources about - How to create new python file with increament number, if doesn't exist? - comp.lang.python

Resources last updated: 3/10/2016 12:58:09 PM