python os 模块

in this tutorial, you will learn how to work along with Python's os module.

Table of Contents

Introduction

Basic Functions

List Files / Folders in Current Working Directory

Change working Directory

Create Single and Nested Directory Structure

Remove Single and Nested Directory Structure Recursively

Example with Data Processing

Conclusion

Introduction

Python is one of the most frequently used languages in recent times for various tasks such as data processing, data analysis, and website building. In this process, there are various tasks that are operating system dependent. Python allows the developer to use several OS-dependent functionalities with the Python module os. This package abstracts the functionalities of the platform and provides the python functions to navigate, create, delete and modify files and folders. In this tutorial one can expect to learn how to import this package, its basic functionalities and a sample project in python which uses this library for a data merging task.

Some Basic Functions

Let's explore the module with some example code.

Import the library:

importos

Let's get the list of methods that we can use with this module.

print(dir(os)) 

Output:

['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getppid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', 'path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace', 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st', 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'supports_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_size', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'write']

Now, using the getcwd method, we can retrieve the path of the current working directory.

print(os.getcwd()) 

Output:

C:\Users\hpandya\OneDrive\work\StackAbuse\os_python\os_python\Project 

List Folders and Files

Let's list the folders/files in the current directory using listdir:

print(os.listdir()) 

Output:

['Data', 'Population_Data', 'README.md', 'tutorial.py', 'tutorial_v2.py']

As you can see, I have 2 folders: Data and Population_Data. I also have 3 files: README.mdmarkdown file, and two Python files namely, tutorial.py and tutorial_v2.py.

In order to get the entire tree structure of my project folder, let's write a function and then use os.walk() to iterate over all the files in each folder of the current directory.

# function to list files in each folder of the current working directorydeflist_files(startpath):forroot, dirs, filesinos.walk(startpath):# print(dirs)ifdir!='.git':            level = root.replace(startpath,'').count(os.sep)            indent =' '*4* (level)            print('{}{}/'.format(indent, os.path.basename(root)))            subindent =' '*4* (level +1)forfinfiles:                print('{}{}'.format(subindent, f))

Call this function using the current working directory path, which we saw how to do earlier:

startpath = os.getcwd() 

list_files(startpath) 

Output:

Project/ 

    README.md

    tutorial.py

    tutorial_v2.py

    Data/

        uscitiesv1.4.csv

    Population_Data/

        Alabama/

            Alabama_population.csv

        Alaska/

            Alaska_population.csv

        Arizona/

            Arizona_population.csv

        Arkansas/

            Arkansas_population.csv

        California/

            California_population.csv

        Colorado/

            Colorado_population.csv

        Connecticut/

            Connecticut_population.csv

        Delaware/

            Delaware_population.csv

        ...

Note: The output has been truncated for brevity.

As seen from the output, the folders' names are ended with a / and the files within the folders have been indented four spaces to the right. The Data folder has one csv file named uscitiesv1.4.csv. This file has data about population for each city in the United States. The folder Population_Datahas folders for States, containing separated csv files for population data for each state, extracted from uscitiesv1.4.csv.

Change Working Directory

Let's change the working directory and enter into the directory of data with the state of "New York".

os.chdir('Population_Data/New York')

Now let's run the list_files method again, but in this directory.

list_files(os.getcwd()) 

Output:

NewYork/NewYork_population.csv

As you can see, we have entered the New York folder under Population_Data folder.

Create Single and Nested Directory Structure

Now, let's create a new directory called testdir in this directory.

os.mkdir('testdir')

list_files(os.getcwd()) 

Output:

NewYork/NewYork_population.csv    testdir/

As you can see, it creates the new directory in the current working directory.

Let's create a nested directory with 2 levels.

os.mkdir('level1dir/level2dir')

Output:

Traceback (most recentcalllast):File"<ipython-input-12-ac5055572301>", line1,in    os.mkdir('level1dir/level2dir')FileNotFoundError: [WinError3] Thesystemcannot find thepathspecified:'level1dir/level2dir'

Subscribe to our Newsletter

Get occassional tutorials, guides, and reviews in your inbox. No spam ever. Unsubscribe at any time.

Subscribe

We get an Error. To be specific, we get a FileNotFoundError. You might wonder, why a FileNotFound error when we are trying to create a directory.

The reason: the Python module looks for a directory called level1dir to create the directory level2dir. Since level1dir does not exist, in the first place, it throws a FileNotFoundError.

For purposes like this, the mkdirs() function is used instead, which can create multiple directories recursively.

os.makedirs('level1dir/level2dir')

Check the current directory tree,

list_files(os.getcwd()) 

Output:

NewYork/NewYork_population.csv    level1dir/        level2dir/    testdir/

As we can see, now we have two subdirectories under New York folder. testdir and level1dir. level1dir has a directory underneath called level2dir.

Remove Single and Multiple Directories Recursively

The os module also had methods to modify or remove directories, which I'll show here.

Now, let's remove the directories we just created using rmdir:

os.rmdir('testdir')

Check the current directory tree to verify that the directory no longer exists:

list_files(os.getcwd()) 

Output:

NewYork/NewYork_population.csv    level1dir/        level2dir/

As you can see, testdir has been deleted.

Let's try and delete the nested directory structure of level1dir and level2dir.

os.rmdir('level1dir')

Output:

OSError  Traceback (most recentcalllast)  in()----> 1 os.rmdir('level1dir')OSError: [WinError145] Thedirectoryisnotempty:'level1dir'

As seen, this throws a OSError and rightly so. It says level1dir directory is not empty. That is correct because it has level2dir underneath it.

With the rmdir method it is not possible to remove a non-empty directory, similar to the Unix command-line version.

Just like the makedirs() method, let's try rmdirs(), which recursively removes directories in a tree structure.

os.removedirs('level1dir/level2dir')

Let's see the directory tree structure again:

list_files(os.getcwd()) 

Output:

NewYork/NewYork_population.csv

This brings us to the previous state of the directory.

Example with Data Processing

So far we have explored how to view, create, and remove a nested directory structure. Now let's see an example of how the os module helps in data processing.

For that let's go one level up in the directory structure.

os.chdir('../')

With that, let's again view the directory tree structure.

list_files(os.getcwd()) 

Output:

Population_Data/ 

    Alabama/

        Alabama_population.csv

    Alaska/

        Alaska_population.csv

    Arizona/

        Arizona_population.csv

    Arkansas/

        Arkansas_population.csv

    California/

        California_population.csv

    Colorado/

        Colorado_population.csv

    Connecticut/

        Connecticut_population.csv

    Delaware/

        Delaware_population.csv

...

Note: The output has been truncated for brevity.

Let's merge the data from all of the states, iterating over the directory of each state and merging the CSV files likewise.

importosimportpandasaspd# create a list to hold the data from each statelist_states = []# iteratively loop over all the folders and add their data to the listforroot, dirs, filesinos.walk(os.getcwd()):iffiles:        list_states.append(pd.read_csv(root+'/'+files[0], index_col=None))# merge the dataframes into a single dataframe using Pandas librarymerge_data = pd.concat(list_states[1:], sort=False)

Thanks in part to the os module we were able to create merge_data, which is a dataframe containing population data from every state.

Conclusion

In this article, we briefly explored different capabilities of Python's built-in os module. We also saw a brief example of how the module can be used in the world of Data Science and Analytics. It is important to understand that os has a lot more to offer, and based on the need of the developer a much more complex logic can be constructed.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,776评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,527评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,361评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,430评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,511评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,544评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,561评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,315评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,763评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,070评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,235评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,911评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,554评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,173评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,424评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,106评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,103评论 2 352

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,319评论 0 10
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,451评论 0 13
  • 又到了秋高气爽的季节, 是时候该吃螃蟹了呢~ 丰腴肥硕的蟹黄蟹膏, 白嫩多汁的蟹肉, 哎呀呀呀呀呀~ 话不多说,赶...
    光明安安阅读 446评论 0 0
  • 1、简介 Swift中类或结构体可以对已有的运算符进行自定义实现,赋予另外一种功能。可以成为运算符函数,即运算符重...
    SuperDawn_0828阅读 2,061评论 0 3
  • 作为传统的中国人,春节的唯一活动,感觉还是打麻将。一家人聚在一起,茶余饭后就开始打了起来。 平时除了上班就是带娃的...
    宇之歆然阅读 233评论 0 1