||
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))
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-9-27 08:54
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社