gll89的个人博客分享 http://blog.sciencenet.cn/u/gll89

博文

python--new functions

已有 1834 次阅读 2017-4-26 10:18 |个人分类:Python|系统分类:科研笔记

1. Copy a file to another path

   >>>from shutil

   >>>shutil.copyfile(src, dst)

Recursively copy an entire directory tree rooted at src to the destinationdirectory, named by dst, which must not already exist

  >>>shutil.copytree(src, dst)    #dst must not exist


Get the absolute path

>>>import os

>>>def absoluteFilePaths(directory):

>>>    for dirpath,_,filenames in os.walk(directory):

>>>        for f in filenames:

>>>            yield os.path.abspath(os.path.join(dirpath, f))



2. iterate a DataFrame without its column

  >>> for value in df.values:

  write a DataFrame into a CSV file without column name

  >>> df.to_csv('filename.csv', header =False)  # header = False

3. convert other type to a string

   >>>vehicles = ["car", "truck", "tractor"]# Convert list to string with join.

   >>>result = "".join(vehicles)

   >>>print(result)

   Output: cartrucktractor

4. Check if a directory exists, create it if necessary

   First way:      

   >>>import osfile_path ="/my/directory/filename.txt"

   >>>directory = os.path.dirname(file_path)

   >>>try:    

   >>>    os.stat(directory)

   >>>except:    

   >>>    os.mkdir(directory)

   Second way:  

   >>>if not os.path.exists(directory):    

   >>>    os.makedirs(directory)

5. print a line in for-loop

  >>> for i in range(10):

  >>>    print(i),    #output is 0,1,2,3,4,5,6,7,8,9


6. Get all the files with a certain extension

   >>>import os
   >>>for root, dirs, files in os.walk('/data/data2/Linlin/Codes/ADNIProcess'):
   >>>    for file in files:
   >>>        if file.endswith(".py"):
   >>>            print(os.path.join(root, file))

   

   

   

   

   

   



https://blog.sciencenet.cn/blog-1969089-1051263.html

上一篇:Atom常用插件以及安装
下一篇:GoogLeNet
收藏 IP: 128.227.206.*| 热度|

1 haipengzhangdr

该博文允许注册用户评论 请点击登录 评论 (0 个评论)

数据加载中...

Archiver|手机版|科学网 ( 京ICP备07017567号-12 )

GMT+8, 2024-7-26 14:31

Powered by ScienceNet.cn

Copyright © 2007- 中国科学报社

返回顶部