![]() |
How to specify the destination folder - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to specify the destination folder (/thread-18528.html) |
How to specify the destination folder - SriMekala - May-21-2019 Hi, I read some comma separated data from the web, and want to write into a csv file. I open a new CSV file write data (df) in it, but I could not be able to specify the destinated folder. How to specify my desination folder is :"D:\myproject" # csv new (create) file fr=open('newcsvdata.csv','w',newlin='') fr.write(df) fr.close() RE: How to specify the destination folder - DeaD_EyE - May-21-2019 Use a context manager to open a file. Just give the whole destination path, to save the file somewhere. You can use relative paths, then the current working directory is your start point. Absolute paths begins with a slash and they are independent from current working directory. with open('your_folder/yourfile.csv', 'w') as fd: # fd is the resulting file object # fd is closed automatic when leaving the block (context manager)To manipulate paths, you should use the pathlib. from pathlib import Path directory = Path('target_directory') # task write files with 0.csv, 1.csv, 2.csv ... for name in range(0, 10): name = str(name) destination = (directory / name).with_suffix('.csv') with destination.open('w') as fd: # code to write content passor globbing like you do it in the shell: from pathlib import Path directory = Path('target_directory') for file in directory.glob('*.csv'): with file.open() as fd: # code to read content pass |