Frequently Used Scripts - python - files, string, dates

In this post:

  • Python loop files in current folder with listdir
  • Python loop over files with os.walk()
  • Split filenames with python
  • Rename Files
  • Date format and extraction
  • Python file read and write
  • Python strings

You can read also : Frequently Used Scripts - Frequently Used Scripts - python pil

Python loop files in current folder with listdir

Listing files in a single folder by using os.listdir()

import os  

for file in os.listdir('.'):
    if os.path.isfile(file ):
       print (file )

Python loop over files with os.walk()

Listing all files in a folder recursively and subfolders

import os

indir = r'C:\Users\user'
for root, dirs, filenames in os.walk(indir):
   for filename in filenames:
       print (filename)

Split filenames with python

Python getting the file name and folder name for a given file path

import os

file =  'C:\\Users\\user\\Desktop\\test.txt'
print (os.path.basename(file))                      #test.txt
print (os.path.dirname(file))                       #C:\Users\user\Desktop
print (os.path.splitext( file ))                    #('C:\\Users\\user\\Desktop\\test', '.txt')
print (os.path.splitext( os.path.basename(file)))   #('test', '.txt'
  • result
test.txt
C:\Users\user\Desktop
('C:\\Users\\user\\Desktop\\test', '.txt')
('test', '.txt')

Rename Files

Rename all files starting with examplepattern in current folder with os.rename and remove examplepattern

import os
for filename in os.listdir("."):
   if filename.startswith("examplepattern"):
       os.rename(filename, filename[7:])
  • before
$ ls
examplepattern_file.txt  examplepattern_file2.txt
  • after
$ ls
file.txt  file2.foo

Date format and extraction

Python getting today date, adding or subtracting days, date formats:

import time
import datetime

#get today date
today = datetime.date.today()
print ("Today", today )

#date format
print (today.strftime("year: %Y, shor year: %y, month: %m, day: %d") )


#delay
seconds = 3.1
time.sleep(seconds)
print ("boo")

#add 30 days to today
day = datetime.timedelta(days=30)
print ("30 days + today:", today + day)

Python file read and write

Python getting today date, adding or subtracting days, date formats:

#read file 
filePath = "C:\\Users\\user\\Desktop\\test.txt"
for line in open(filePath):
    if 'test' in line:
        print (line[:-1])

#append line to file
#\n is converted as line separator for the OS
with open(filePath, 'a') as file:
    file.write('\nsample data')

#overrite file content and add new line
file = open(filePath, 'w')
file.write('hi there\n')  
file.close() 

Python strings

Declaration and usage:

simpleString = "String"   # a newline character
rawString = r"C:\Users\user\test.txt"  # windows path escaped
quotesDouble = "I'm a string"  # single quote in double quotes
quotesSingle = 'I\'m a "string"'  # double quote in single quotes and escaped
#multi lines strings
multiStringDouble = """
line1
line2
line3
"""
multiStringSingle = '''
line4
line5
'''
#String addition
print(multiStringDouble +  multiStringSingle)
#Substring
print(rawString[:5]) #first 5 characters
print(rawString[-10:]) #last 10 characters

#string search
string = 'test'
if string in rawString[-10:]:
    print ("'%s' found in last 10 characters"%string)

#string replace
str = "Java is good, java is clever, java is best"
print (str.replace("java", "python")) #replace all
print (str.replace("java", "python", 1)) #replace first one
#Java is good, python is clever, python is best
#Java is good, python is clever, java is best