In this post:

  • Read files with python
  • Write files with python
  • Python loop/iterate files
  • Rename files with python
  • Python split filename into name and extension
  • Python get file path

Read files with python

Read an csv file using python. The code below opens a file by using it's full absolute path and read the file line by line:

csv = open("/home/user/my.csv")
for line in csv:
    print(line)

Read csv file with python row by row, column by column:

csv = open("/home/user/my.csv")
for line in csv:
    print(line.strip().split(";"))

Write files with python

You can write information to files in python with two modes:

  • append - this mode will add new lines without deleting the information of the file
csv = open("/home/user/Desktop/my.csv", 'a')

for i in range(0, 20):
    element = str(i) + ";"
    written = csv.write(element)
  • truncate - this mode will delete old information
csv = open("/home/user/Desktop/my.csv", 'a')

for i in range(0, 20):
    element = str(i) + ";"
    written = csv.write(element)

Python loop/iterate files

You can list all files in the current folder(the one of the script) by this code:

import os

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

list all files in a specific folder by absolute path. This code list all objects in the folder and then check if the object is a file. If yes then print out the result:

import os

path = '/home/user/Documents/'

for fn in os.listdir(path):
    if os.path.isfile(path + fn):
       print (fn)

Rename files with python

If you need to rename files in python you can use code like this one:

import os

for filename in os.listdir("."):
   if filename.startswith("prefix"):
       os.rename(filename, filename[6:])

Explanation:

  • This code loop over all files in the current folder
  • search for files starting with: prefix
  • then use os.rename - in order to remove the prefix from the name
    • Replace current name with current name without first six characters

Python split filename into name and extension

This code below list all files in the current folder as:

name + extension
import os

for filename in os.listdir("."):
    name = os.path.splitext( os.path.basename(filename))
    print(name)

result:

('my_file', '.txt')
('__init__', '.py')

Python get file path

You can get the current folder or a given file's folder by using:

  • os.path.abspath - return the absolute path of a file
  • os.path.realpath - return the relative path of a file
  • os.getcwd() - return current folder of the running script
import os

path = '/home/user/Documents/Programming'

abs_path = os.path.dirname(os.path.abspath(path))
dir_path = os.path.dirname(os.path.realpath(path))
cur_path = os.getcwd()

print(abs_path)
print(dir_path)
print(cur_path)

result:

/home/user/Documents
/home/user/Documents
/home/user/PycharmProjects/python/test/File