Get file version using python

Python method to get file version information company name and product name

This article is an example of how python gets file version information, company name, and product name. The details are as follows:

This python code gets the file version information, company name, and product name. The rest of the information is in the returned dictionary. The specific code is as follows:

 def _getCompanyNameAndProductName(self, file_path): """ Read all properties of the given file return them as a dictionary. """ propNames = ('Comments', 'InternalName', 'ProductName', 'CompanyName', 'LegalCopyright', 'ProductVersion', 'FileDescription', 'LegalTrademarks', 'PrivateBuild', 'FileVersion', 'OriginalFilename', 'SpecialBuild') props = try: # backslash as parm returns dictionary of numeric info corresponding to VS_FIXEDFILEINFO struc fixedInfo = win32api.GetFileVersionInfo(file_path, '\') props['FixedFileInfo'] = fixedInfo props['FileVersion'] = "%d.%d.%d.%d" % (fixedInfo['FileVersionMS'] / 65536, fixedInfo['FileVersionMS'] % 65536, fixedInfo['FileVersionLS'] / 65536, fixedInfo['FileVersionLS'] % 65536) # VarFileInfoTranslation returns list of available (language, codepage) # pairs that can be used to retreive string info. We are using only the first pair. lang, codepage = win32api.GetFileVersionInfo(file_path, '\VarFileInfo\Translation')[0] # any other must be of the form StringfileInfo%04X%04Xparm_name, middle # two are language/codepage pair returned from above strInfo = <> for propName in propNames: strInfoPath = u'\StringFileInfo\%04X%04X\%s' % (lang, codepage, propName) ## print str_info strInfo[propName] = win32api.GetFileVersionInfo(file_path, strInfoPath) props['StringFileInfo'] = strInfo except: pass if not props["StringFileInfo"]: return (None, None) else: return (props["StringFileInfo"]["CompanName"], props["StringFileInfo"]["ProductName"]) 

I hope this article has helped you with your Python programming.

Читайте также:  Параллельный запуск скрипта php

Источник

Python code to locate the most recent file version in a directory

One approach to solve the issue is to use a specific method, where the last element of a list is extracted. Alternatively, another solution involves fetching the latest folder created; however, this method is not recommended as other applications may create a folder before it is fetched. In order to avoid iterating over all files in a directory twice, it is suggested to use a set instead of a list. Additionally, using a set would allow for further simplification.

Find the Latest file version in a folder using Python

import glob latest = sorted(glob.glob('dd19_15_00_an1+\.avi'))[-1] 

It is acceptable to use a normal sort for versions that have zero padding. However, if your versions lack zero padding, a natural sort is required, which can make things more complex.

  1. Create a hierarchical depiction of your documents, in a recursive manner.
  2. Do the search

To handle suffixes other than «02», a regular expression like 2+ can be used. However, for different suffixes or prefixes, it may be necessary to compute the levenstein distance in specific intervals.

How to get the latest file from folder using python, Find centralized, trusted content and collaborate around the technologies you use most.

Python name of latest folder created in a directory

You can do something like this:

import os directory = '.' # current dir folders = os.walk(directory).next()[1] creation_times = [(folder, os.path.getctime(folder)) for folder in folders] creation_times.sort(key=lambda x: x[1]) # sort by creation time 

Afterwards, you may select the final item from this collection.

most_recent = creation_times[-1][0] 

Retrieving the most recently created folder can be problematic as another application might create a folder just before you attempt to retrieve it. However, if you wish to experiment with the code, the solution presented by elyase is acceptable.

Python — How to get last modified file in a directory?, get the list of files; get the time for each of them (also check os.path.getmtime() for updates) use datetime module to get a value to compare …

Read most recent excel file from folder PYTHON

from pathlib import Path # Save all .xlsx files paths and modification time into paths paths = [(p.stat().st_mtime, p) for p in Path("path/to/folder").iterdir() if p.suffix == ".xlsx"] # Sort them by the modification time paths = sorted(paths, key=lambda x: x[0], reverse=True) # Get the last modified file last = paths[0][1] 

Please be aware that last is classified as a Path. In case you require it to be in a string format, kindly modify the final line.

import os # list all .xlsx files in absolute directory files = (os.path.abspath(file) for file in os.listdir('/path/to/PYTHON') if file.endswith('.xlsx')) # get their last updated time files_and_updated_time = ((file, os.path.getmtime(file)) for file in files) # sort out the lastest updated xlsx last_updated_xlsx = sorted(files_and_updated_time, key=lambda x: x[1], reverse=True) # check if this said xlsx exists # if so, store its absolute path in `result` if last_updated_xlsx: result = last_updated_xlsx[0][0] else: result = None 

I am unsure of the operating system you are using, but I do have a solution that works for Linux and Raspberry Pi. Perhaps, with a small modification, this solution could also be applied to Windows.

  • Utilize the datetime library to obtain the current date.
  • Employ the os library to locate a document within a designated directory or folder.
import os from datetime import datetime # This gets today's date in string with the format of 2021-12-31. today = datetime.today().strftime('%Y-%m-%d') # Assume your filename is only today's date and the extension at the end. path = '/home/pi/' + today + '.xlsx' # If there's a same filename found in this path. if os.path.exists(path): print("File found") # Gets the filename from the path and store it in the 'filename' variable. filename = os.path.basename('/home/pi/' + path + '.xlsx') else: print("File not found") 

How to find the latest file in a directory with Python, It’s actually a bug, or at least an omission, in the program code you grabbed. os.path.getmtime takes a full path to a file, so the lambda is trying to …

Get the latest file in directories taking a long to run

You may be unaware, but there is a loop in your code that is redundant. Specifically, this particular code segment:

for filename in files: if filename.endswith('.zip'): list_of_files = glob.glob(dirname + '\*.zip') 

The glob.glob fetches all zip files from the current directory, indicated by dirname as the root path. If there are 10 zip files in that directory, glob.glob will be executed 10 times. However, only the first occurrence of the file will be added to the list.

The complete inner loop can be condensed to a statement similar to this.

for (dirname, dirs, files) in os.walk(cwd): list_of_files = glob.glob(dirname + '\*.zip') if len(list_of_files) == 0: continue latest_file = max(list_of_files, key=os.path.getctime) if latest_file not in list_of_latest: list_of_latest.append(latest_file) 

That inner loop is unnecessary.

You’re scanning through all files in a directory twice — initially using:

latest_file = max(list_of_files, key=os.path.getctime) 

What you probably want is:

for (dirname, dirs, files) in os.walk(cwd): list_of_files = glob.glob(dirname + '\*.zip') latest_file = max(list_of_files, key=os.path.getctime) if latest_file not in list_of_latest: list_of_latest.append(latest_file) 

By using a set instead of a list for list_of_latest , it would enable additional simplification.

list_of_latest = set() for (dirname, dirs, files) in os.walk(cwd): list_of_files = glob.glob(dirname + '\*.zip') latest_file = max(list_of_files, key=os.path.getctime) list_of_latest.add(latest_file) 

Python newest file in a directory, Python get most recent file in a directory with certain extension. 0. Finding latest file in a folder using python. Related. 5807. How do I get the directory where a …

Источник

How to get Details of a File using Python

How to get Details of a File using Python

Because Python is a server-side language, it can access and manipulate the file system just like any other language.

That means that you can use Python to get information about files, such as their size, creation date, and more.

In this post, we’ll learn how you can use Python to get details of a file on your file system.

Import the os module

To get file details in Python, you can use the os module.

The os module provides a number of functions for interacting with the file system.

First, import the os module:

Get the file size

Now that you’ve imported the os module, you can use the os.path.getsize() function to get the size of a file.

First define a file path to the file you want to get the size of, and keep in mind that the path will be different depending on your operating system.

For these purposes, we’ll continue to use the Mac/Linux file path.

Then use the os.path.getsize() function to get the size of the file:

This will return the size of the file in bytes.

Get the file creation date

To get the creation date of a file, you can use the os.path.getctime() function.

This returns the number of seconds since the epoch, which is January 1, 1970.

Get the file modification date

To get the modification date of a file, you can use the os.path.getmtime() function.

Likewise, this returns the number of seconds since the epoch.

How to get the stats of a file

Another thing you can fetch about a file is its stats.

The os.stat() function returns a stat_result object that contains a number of attributes about the file.

These attributes include the file size, file owner id, file group id, permissions, and more.

Conclusion

In this post, we learned how to get file details in Python.

This included getting the size of a file, the creation date, the modification date, and the stats of a file.

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Give feedback on this page , tweet at us, or join our Discord !

Источник

Оцените статью