Amber.G
Amber.G

Reputation: 1503

Get a text file name

7 on Windows 7 platform.

I would like to complete two steps,

  1. generate a text file with the name of current date and time
  2. get the size of this file.

So far, I could generate the file and know the command to get the size. The question is, before I use the command to get the text file size, I need to type in the file name. But I have no idea how to get it. Please see the two steps code in below for detail.

1) To generate a text file with name of current date and time:

import datetime
import os
import glob

def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
    return datetime.datetime.now().strftime(fmt).format(fname=fname)

with open(timeStamped('Log.txt'),'w') as outf:
     print outf

2) the command to get the file size:

size = os.path.getsize("path/file name")

I am stuck at second step: ("path/file name") because I cannot get the name of the text file.

Please advice. Thanks.

Upvotes: 1

Views: 1378

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177674

Just save the name of the file:

import datetime
import os

def timeStamped(fname, fmt='%Y-%m-%d-%H-%M-%S_{fname}'):
    return datetime.datetime.now().strftime(fmt).format(fname=fname)

fname = timeStamped('Log.txt')
with open(fname,'w') as outf:
     outf.write('something')

size = os.path.getsize(fname)
print(size)

Upvotes: 2

Related Questions