Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,149
» Latest member: GalacticNuddy
» Forum threads: 21,799
» Forum posts: 22,673

Full Statistics

Online Users
There are currently 588 online users.
» 0 Member(s) | 583 Guest(s)
Applebot, Baidu, Bing, Google, Yandex

 
  [Tut] Extract File Name From the Path, No Matter What the os/path Format
Posted by: xSicKxBot - 05-06-2022, 09:46 AM - Forum: Python - No Replies

Extract File Name From the Path, No Matter What the os/path Format

Summary: os.path.basename(path) enables us to get the file name from the path, no matter what the os/path format. Another workaround is to use the ntpath module, which is equivalent to os.path.


✨Problem: How to extract the filename from a path, no matter what the operating system or path format is?

For example, let’s suppose that you want all the following paths to return demo.py:

➤ C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py
➤ /home/username/Desktop/codes/demo.py
➤ /home/username/Desktop/../demo.py

Expected Output in each case:

demo.py

Recommended: How To Get The Filename Without The Extension From A Path In Python?

Let us dive into the solutions without further delay.

Method 1: Using os.path.basename


os.path.basename is a built-in method of the os module in Python that is used to derive the basename of a file from its path. It accepts the path as an input and then returns the basename of the file. Thus, to get the filename from its path, this is exactly the function that you would want to use.

Example 1: In Windows

import os
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
print(os.path.basename(file_path)) # OUTPUT: demo.py

Example 2: In Linux


Caution: If you use the os.path.basename() function on a POSIX system in order to get the basename from a Windows-styled path, for example: “C:\\my\\file.txt“, the entire path will be returned.

Tidbit: os.path.basename() method actually uses the os.path.split() method internally and splits the specified path into a head and tail pair and finally returns the tail part. 

Method 2: Using the ntpath Module


The ntpath module can be used to handle Windows paths efficiently on other platforms. os.path.basename function does not work in all the cases, like when we are running the script on a Linux host, and you attempt to process a Windows-style path, the process will fail.

This is where the ntpath module proves to be useful. Generally, the Windows path uses either the backslash or the forward-slash as a path separator. Therefore, the ntpath module, equivalent to the os.path while running on Windows, will work for all the paths on all platforms.

In case the file ends with a slash, then the basename will be empty, so you can make your own function and deal with it:

import ntpath def path_foo(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) paths = [r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py', r'/home/username/Desktop/codes/demo.py', r'/home/username/Desktop/../demo.py']
print([path_foo(path) for path in paths]) # ['demo.py', 'demo.py', 'demo.py']

Method 3: Using pathlib.Path()


If you are using Python 3.4 or above, then the pathlib.Path() function of the pathlib module is another option that can be used to extract the file name from the path, no matter what the path format. The method takes the whole path as an input and extracts the file name from the path and returns the file name.

from pathlib import Path
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
file_name = Path(file_path).name
print(file_name) # demo.py

Note: The .name property followed by the pathname is used to return the full name of the final child element in the path, regardless of whatever the path format is and regardless of whether it is a file or a folder.

?Bonus Tip: You can also use Path("File Path").stem to get the file name without the file extension.

Example:

from pathlib import Path
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
file_name = Path(file_path).stem
print(file_name) # demo

Method 4: Using split()


If you do not intend to use any built-in module to extract the filename irrespective of the OS/platform in use, then you can simply use the split() method.

Example:

import os
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
head, tail = os.path.split(file_path)
print(tail) # demo.py

Explanation: In the above example os.path.split() method is used to split the entire path string into head and tail pairs. Here, tail represents/stores the ending path name component, which is the base filename, and head represents everything that leads up to that. Therefore, the tail variable stores the name of the file that we need.

A Quick Recap to split():
split() is a built-in method in Python that splits a string into a list based on the separator provided as an argument to it. If no argument is provided, then by default, the separator is any whitespace.

Learn more about the split() method here.

Alternatively, for more accurate results you can also use a combination of the strip() and split() methods as shown below.

file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py'
f_name = file_path.strip('/').strip('\\').split('/')[-1].split('\\')[-1]
print(f_name)
# demo.py

Explanation: The strip method takes care of the forward and backward slashes, which makes the path string fullproof against any OS or path format, and then the split method ensures that the entire path string is split into numerous strings within a list. Lastly, we will just return the last element from this list to get the filename.

Method 5: Using Regex


If you have a good grip on regular expressions then here’s a regex specific solution for you that will most probably work on any OS.

import re
file_path = r'C:\Users\SHUBHAM SAYON\Desktop\codes\\'
def base_name(path): basename = re.search(r'[^\\/]+(?=[\\/]?$)', path) if basename: return basename.group(0) paths = [r'C:\Users\SHUBHAM SAYON\Desktop\codes\demo.py', r'/home/username/Desktop/codes/demo.py', r'/home/username/Desktop/../demo.py']
print([base_name(path) for path in paths]) # ['demo.py', 'demo.py', 'demo.py']

Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

Conclusion


To sum thungs up, you can use one of the following methods to extract the filename from a given path irrespective of the OS/path format:

  • os.path.basename('path')
  • ntpath.basename()
  • pathlib.Path('path').name
  • os.path.split('path')
  • using regex

Please stay tuned and subscribe for more interesting articles!


To become a PyCharm master, check out our full course on the Finxter Computer Science Academy available for free for all Finxter Premium Members:




https://www.sickgaming.net/blog/2022/05/...th-format/

Print this item

  [Oracle Blog] The Arrival of Java 14!
Posted by: xSicKxBot - 05-06-2022, 09:46 AM - Forum: Java Language, JVM, and the JRE - No Replies

The Arrival of Java 14!

Follow OpenJDK on Twitter Download Oracle OpenJDK Download Oracle JDK Oracle is proud to announce the general availability of Java 14 representing the fifth feature release as part of the six-month cadence. This level of predictability, for over two years now, allows developers to more easily manage...

https://blogs.oracle.com/java/post/the-a...of-java-14

Print this item

  (Indie Deal) TAG, Kasedo Good Shepherd & Yogscast Sales
Posted by: xSicKxBot - 05-06-2022, 09:46 AM - Forum: Deals or Specials - No Replies

TAG, Kasedo Good Shepherd & Yogscast Sales

Team17 Giveaways
[www.indiegala.com]

https://www.youtube.com/watch?v=2d22lPJm6jY
TAG, Kasedo Good Shepherd & Yogscast Sales
[www.indiegala.com]
[www.indiegala.com]
[www.indiegala.com]
[www.indiegala.com]
Save an EXTRA 30% for every bundle & an extra 15% for every store purchase when paying with any supported crypto
Stay Inside, Stay Safe and Enjoy Good Games.
Check out IndieGala on Twitter, YouTube & Facebook[www.facebook.com]


https://steamcommunity.com/groups/indieg...4853609343

Print this item

  (Free Game Key) Terraforming Mars - Free Epic Game
Posted by: xSicKxBot - 05-06-2022, 09:46 AM - Forum: Deals or Specials - No Replies

Terraforming Mars - Free Epic Game

Visit the store page and add the game to your account:

Terraforming Mars[store.epicgames.com]

The game is free to keep until May 12th 2022 - 15:00 UTC.

Next week's freebie:
Jotun: Valhalla Edition
Prey

We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: ✔️HumbleBundle Partner[www.humblebundle.com] Epic Tag: GrabFreeGames


https://steamcommunity.com/groups/GrabFr...6386228581

Print this item

  PC - POSTAL 4: No Regerts
Posted by: xSicKxBot - 05-06-2022, 09:46 AM - Forum: New Game Releases - No Replies

POSTAL 4: No Regerts



Several years have passed since the events that devastated the once proud town remembered as Paradise. The only two to walk away from the cataclysm unscathed, the hapless everyman known as the POSTAL Dude and his loyal companion Champ, drive aimlessly through the scorching deserts of Arizona looking for a new place to call home. After a fortuitous gas station rest stop ends with their car, trailer home, and the rest of their worldly possessions stolen, all the Dude’s seemingly got left to his name is his canine cohort and his bathrobe, and neither of them smells all that great. However, on the horizon, the duo glimpses an unfamiliar and dazzling town that beckons to them. What untold prospects lie within? Fame? Fortune? Maybe a bidet or two? Edensin awaits. POSTAL 4: No Regerts is a satirical and outrageous comedic open world first person shooter and the long-awaited true sequel to what’s been fondly dubbed as "The Worst Game Ever™", POSTAL 2! (No third game is known to exist.)

Publisher: Running With Scissors

Release Date: Apr 20, 2022




https://www.metacritic.com/game/pc/postal-4-no-regerts

Print this item

  [Oracle Blog] JDK 14 Has Been Released
Posted by: xSicKxBot - 05-05-2022, 07:23 AM - Forum: Java Language, JVM, and the JRE - No Replies

JDK 14 Has Been Released

JDK 14 is live! Download it from the Java SE Downloads page. See the JDK 14 Release Notes for detailed information about this release. The following are some of the important additions and updates in Java SE 14 and JDK 14: Switch Expressions is now a permanent feature. See JEP 361: Switch Expression...

https://blogs.oracle.com/java/post/jdk-1...n-released

Print this item

  [Tut] How to Measure Elapsed Time in Python?
Posted by: xSicKxBot - 05-05-2022, 07:23 AM - Forum: Python - No Replies

How to Measure Elapsed Time in Python?

Summary: You can evaluate the execution time of your code by saving the timestamps using time.time() at the beginning and the end of your code. Then, you can find the difference between the start and the end timestamps that results in the total execution time.


Problem: Given a Python program; how will you measure the elapsed time ( the time taken by the code to complete execution)?

Consider the following snippet:

import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x p = perimeter(8)
print("Perimeter: ", p)
a = area(8)
print("Area: ", a)
  • Challenges:
    • How will you find the time taken by each function in the above program to execute?
    • How will you compute the total time elapsed by the entire code?

Tidbit: sleep() is a built-in method of the time module in Python that is used to delay the execution of your code by the number of seconds specified by you.

Now, let us conquer the given problem and dive into the solutions.

Method 1: Using time.time()


time.time() is a function of the time module in Python that is used to get the time in seconds since the epoch. It returns the output, i.e., the time elapsed, as a floating-point value.

The code:

import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = time.time() start = time.time()
p = perimeter(8)
end = time.time()
print("Perimeter: ", p)
print("Time Taken by perimeter(): ", end - start) start = time.time()
a = area(8)
end = time.time()
print("Area: ", a)
print("Time Taken by area(): ", end - start) end = time.time()
print("Total time elapsed: ", end - begin)

Output:

Perimeter: 32
Time Taken by Perimeter(): 5.0040647983551025
Area: 64
Time Taken by area(): 2.0023691654205322
Total time elapsed: 7.006433963775635

Approach:
➤ Keep track of the time taken by each function by saving the time stamp at the beginning of each function with the help of a start variable and using the time() method.
➤ Similarly, the end time, i.e., the timestamp at which a function completes its execution, is also tracked with the help of the time() function at the end of each function.
➤ Finally, the difference between the end and the start time gives the total time taken by a particular function to execute.
➤ To find the total time taken by the entire program to complete its execution, you can follow a similar approach by saving the time stamp at the beginning of the program and the time stamp at the end of the program and then find their difference.

Discussion: If you are working on Python 3.3 or above, then another option to measure the elapsed time is perf_counter or process_time, depending on the requirements. Prior to Python 3.3, you could have used time.clock, however, it has been currently deprecated and is not recommended.

Method 2: Using time.perf_counter()


In Python, the perf_counter() function from the time module is used to calculate the execution time of a function and gives the most accurate time measure of the system. The function returns the system-wide time and also takes the sleep time into account.

import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = time.perf_counter() start = time.perf_counter()
p = perimeter(8)
end = time.perf_counter()
print("Perimeter: ", p)
print("Time Taken by perimeter(): ", end - start) start = time.perf_counter()
a = area(8)
end = time.perf_counter()
print("Area: ", a)
print("Time Taken by area(): ", end - start) end = time.perf_counter()
print("Total time elapsed: ", end - begin)

Output:

Perimeter: 32
Time Taken by perimeter(): 5.0133558
Area: 64
Time Taken by are(): 2.0052768
Total time elapsed: 7.0189293

Caution: The perf_counter() function not only counts the time elapsed along with the sleep time, but it is also affected by other programs running in the background on the system. Hence, you must keep this in mind while using perf_counter for performance measurement. It is recommended that if you utilize the perf_counter() function, ensure that you run it several times so that the average time would give an accurate estimate of the execution time.

Method 3: Using time.process_time()


Another method from the time module used to estimate the execution time of the program is process_time(). The function returns a float value containing the sum of the system and the user CPU time of the program. The major advantage of the process_time() function is that it does not get affected by the other programs running in the background on the machine, and it does not count the sleep time.

import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = time.process_time() start = time.process_time()
p = perimeter(8)
end = time.process_time()
print("Perimeter: ", p)
print("Time Taken by perimeter(): ", end - start) start = time.process_time()
a = area(8)
end = time.process_time()
print("Area: ", a)
print("Time Taken by area(): ", end - start) end = time.process_time()
print("Total time elapsed: ", end - begin)

Output:

Perimeter: 32
Time Taken by perimeter(): 5.141000000000173e-05
Area: 64
Time Taken by area(): 4.1780000000005146e-05
Total time elapsed: 0.00029919000000000473

Method 4: Using Timeit Module


timeit is a very handy module that allows you to measure the elapsed time of your code. A major advantage of using the timeit module is its ability to measure and execute lambda functions by specifying the number of executions.

Note: The timeit module turns off the garbage collection process temporarily while calculating the execution time.

Let us dive into the different methods of this module to understand how you can use it to measure execution time within your code.

4.1 Using timeit.timeit()


Example 1: In the following example, we will have a look at a lambda function being executed with the help of the timeit module such that we will be specifying the number of times this anonymous function will be executed and then calculate the time taken to execute it.

import timeit count = 1 def foo(x): global count print(f'Output for call{count} = {x * 3}') count += 1 a = timeit.timeit(lambda: foo(8), number=3)
print("Time Elapsed: ", a)

Output:

Output for call1 = 24
Output for call2 = 24
Output for call3 = 24
Time Elapsed: 6.140000000000312e-05

Explanation: After importing the timeit module, you can call the lambda function within the timeit.timeit() function as a parameter and also specify the number of times the function will be called with the help of the second parameter, i.e., number. In this case, we are calling the lambda function three times and printing the output generated by the function every time. Finally, we displayed the total time elapsed by the function.

4.2 Using timeit.repeat


Even though the above method allowed us to calculate the execution time of a lambda function, it is not safe to say that the value evaluated by the timeit() function was accurate. To get a more accurate result, you can record multiple values of execution time and then find their mean to get the best possible outcome. This is what timeit.repeat() function allows you to do.

Example:

import timeit count = 1 def foo(x): global count print(f'Output for call{count} = {x * 3}') count += 1 a = timeit.repeat(lambda: foo(8), number=1, repeat=3)
print(a)
s = 0
for i in a: s = s + i
print("Best Outcome: ", s)

Output:

Output for call1 = 24
Output for call2 = 24
Output for call3 = 24
[5.160000000001275e-05, 1.3399999999996748e-05, 1.0399999999993748e-05]
Best Outcome: 7.540000000000324e-05

4.3 Using timeit.default_timer()


Instead of using timeit.timeit() function, we can also use the timeit.default_timer(), which is a better option as it provides the best clock available based on the platform and Python version you are using, thereby generating more accurate results. Using timeit.default_timer() is quite similar to using time.time().

Example:

import timeit
import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = timeit.default_timer() start = timeit.default_timer()
p = perimeter(8)
end = timeit.default_timer()
print("Perimeter: ", p)
print("Time Taken by Perimeter(): ", end - start) start = timeit.default_timer()
a = area(8)
end = timeit.default_timer()
print("Area: ", a)
print("Time Taken by Perimeter(): ", end - start) end = timeit.default_timer()
print("Total time elapsed: ", end - begin)

Output:

Perimeter: 32
Time Taken by Perimeter(): 5.0143883
Area: 64
Time Taken by Perimeter(): 2.0116591
Total time elapsed: 7.0264410999999996

Methdo 5: Using datetime.datetime.now()


The elapsed time can also be calculated using the DateTime.datetime.now() function from the datetime module in Python. The output of the method is represented as days, hours, and minutes. However, the disadvantage of this method is that it is slower than the timeit() module since calculating the difference in time is also included in the execution time.

Example:

import datetime
import time def perimeter(x): time.sleep(5) return 4 * x def area(x): time.sleep(2) return x * x begin = datetime.datetime.now() start = datetime.datetime.now()
p = perimeter(8)
end = datetime.datetime.now()
print("Perimeter: ", p)
print("Time Taken by Perimeter(): ", end - start) start = datetime.datetime.now()
a = area(8)
end = datetime.datetime.now()
print("Area: ", a)
print("Time Taken by Perimeter(): ", end - start) end = datetime.datetime.now()
print("Total time elapsed: ", end - begin)

Output:

Perimeter: 32
Time Taken by Perimeter(): 0:00:05.003221
Area: 64
Time Taken by Perimeter(): 0:00:02.011262
Total time elapsed: 0:00:07.014483

Conclusion


Thus to sum things up, you can use one of the following modules in Python to calculate the elapsed time of your code:

  • The time module
  • The timeit module
  • The datetime module

With that, we come to the end of this tutorial, and I hope you found it helpful. Please subscribe and stay tuned for more interesting articles.

Here’s a list of highly recommended tutorials if you want to dive deep into the execution time of your code and much more:



https://www.sickgaming.net/blog/2022/05/...in-python/

Print this item

  (Indie Deal) MONSTER HUNTER RISE, Obi-Wan (EMEA), Train Deals
Posted by: xSicKxBot - 05-05-2022, 07:23 AM - Forum: Deals or Specials - No Replies

MONSTER HUNTER RISE, Obi-Wan (EMEA), Train Deals

Bestselling MONSTER HUNTER RISE Deal
[www.indiegala.com]
Hunt down a plethora of monsters with distinct behaviors and deadly ferocity. From classic returning monsters to all-new creatures inspired by Japanese folklore, including the flagship wyvern Magnamalo, you’ll need to think on your feet and master their unique tendencies if you hope to reap any of the rewards!

https://www.youtube.com/watch?v=yS4DXKglLRA
Obi Wan, Dovetail & Akupara Sales
[www.indiegala.com]
[www.indiegala.com]
[www.indiegala.com]
Save an EXTRA 30% for every bundle & an extra 15% for every store purchase when paying with any supported crypto
https://www.youtube.com/watch?v=uK7En100og0
Stay Inside, Stay Safe and Enjoy Good Games.
Check out IndieGala on Twitter, YouTube & Facebook[www.facebook.com]


https://steamcommunity.com/groups/indieg...4846225659

Print this item

  News - Star Wars Pinball Table Is On Sale For Its Lowest Price Yet On Star Wars Day
Posted by: xSicKxBot - 05-05-2022, 07:22 AM - Forum: Lounge - No Replies

Star Wars Pinball Table Is On Sale For Its Lowest Price Yet On Star Wars Day

May the Fourth is in full swing today, and when the Star Wars universe isn't dropping a new Obi-Wan trailer it's also revealing some great deals on merchandise. Pinball wizards can grab one such bargain now, as Arcade 1Up's official Star Wars table has been given the Darth Maul treatment with a massive discount. You can get the table for only $420 with promo code MAYTHEFOURTH. The original list price for the table is $750, and major retailers tend to sell it for around $600, so this is a stellar deal.

This table has a cool design featuring promotional art from all three Star Wars trilogies. For more on this cool pinball table, check out our full review of Arcade1Up Star Wars Pinball.

Continue Reading at GameSpot

https://www.gamespot.com/articles/star-w...01-10abi2f

Print this item

  PC - Winter Ember
Posted by: xSicKxBot - 05-05-2022, 07:22 AM - Forum: New Game Releases - No Replies

Winter Ember



You are Arthur Artorias – the sole survivor of a massacre that devastated your family’s legacy and tore them out of the history books. Thought to be dead, you emerge from exile 8 years later, the faceless man kindled by the flame and seeking vengeance. Embark on an adventure unravelling a dark tale filled with twisted characters, centered around a militant religion hell bent on keeping control.
Key Features:
A True Stealth Experience
As Arthur, you must stick to the shadows, infiltrate homes and explore hidden passageways; but, be careful not to be spotted! Choose your playstyle: knocking out enemies may keep them quiet for some time, but they will eventually wake up; a quick slice to the throat may be a more permanent solution, but the bloodstain you leave on the carpet might be a dead giveaway! Keep your wits about you, dispose of bodies, peek through keyholes and pickpocket unsuspecting victims.
Deep Arrow Crafting System
Prepare for your mission by planning your loadout. With over 30 arrows to craft, experimentation is key to your success! Do you craft a smoke arrow to blind your opponent, or do you add on a poison element to create poisonious gas? Use your arrows offensively or defensively: break down weak walls with a blunt arrow to surprise your enemy, or use a rope arrow to reach a higher place and take out your enemies from a distance.
Skill Tree
Customize your playstyle from 3 distinct skill trees – stealth, combat, and utility. Unlock over 70 unique passive and active skills to choose from and seek vengeance your way.
Explore A Dark World
Return home to the cold Victorian town of Anargal, on the verge of technological breakthrough. Infiltrate and explore vast environments brimming with treasure and mystery. From rival gangs to unique characters, approach each scenario in a myriad of ways. Take advantage of the environment, find solutions to every problem, and move past any challenge standing in your way.

Publisher: Blowfish Studios

Release Date: Apr 19, 2022




https://www.metacritic.com/game/pc/winter-ember

Print this item

 
Latest Threads
Black Ops (BO1, T5) DLC's...
Last Post: GalacticNuddy
47 minutes ago
Redacted T6 Nightly Offli...
Last Post: Marlo
2 hours ago
Black Ops 2 Jiggy v4.3 PC...
Last Post: SinjiKoto
2 hours ago
(Free Game Key) Epic Game...
Last Post: xSicKxBot
6 hours ago
News - Paralives’ Success...
Last Post: xSicKxBot
6 hours ago
[°NeW°]⩽United Arab Emira...
Last Post: abhi89
11 hours ago
[°NeW°]⩽Switzerland⟫°TℰℳU...
Last Post: abhi89
Today, 07:53 AM
[°NeW°]⩽Ireland⟫°TℰℳU Cou...
Last Post: abhi89
Today, 06:23 AM
[°NeW°]⩽Chile⟫°TℰℳU Coupo...
Last Post: abhi89
Today, 06:19 AM
[°NeW°]⩽Pakistan⟫°TℰℳU Co...
Last Post: abhi89
Today, 06:16 AM

Forum software by © MyBB Theme © iAndrew 2016