|
| 1 | +In general, to create or retrieve a file on your local system you must use the `open` command. Open has a few different "modes" so let's go through them now. |
| 2 | + |
| 3 | +## 1 Create a file with the `w` mode |
| 4 | +`w` means write as in write-mode. First let's define a random path to a filename that does not yet exist. |
| 5 | +```python |
| 6 | +to_save_dir = "/path/to/save/in/" |
| 7 | +filename = "myfilename.txt" |
| 8 | +full_path = to_save_dir + filename |
| 9 | +``` |
| 10 | +Now let's `open()` that path so we can save it. |
| 11 | + |
| 12 | +```python |
| 13 | +with open(full_path, 'w') as file_object: |
| 14 | + file_object.write("Hello world") |
| 15 | +``` |
| 16 | + |
| 17 | +If we don't want to use `with` we just have to explicitly `close` the `open` call. |
| 18 | + |
| 19 | +```python |
| 20 | +file_object = open(full_path, 'w') |
| 21 | +file_object.write("Hello World") |
| 22 | +file_object.save() |
| 23 | +``` |
| 24 | + |
| 25 | +## 2 Open a file with the `r` mode |
| 26 | +`r` means write as in write-mode. First let's define a random path to a filename that already exists (we created it above). |
| 27 | +```python |
| 28 | +to_save_dir = "/path/to/save/in/" |
| 29 | +filename = "myfilename.txt" |
| 30 | +full_path = to_save_dir + filename |
| 31 | +``` |
| 32 | + |
| 33 | +```python |
| 34 | +with open(full_path, 'r') as file_object: |
| 35 | + contents = file_object.read() |
| 36 | + print(contents) |
| 37 | +``` |
| 38 | + |
| 39 | +If we don't want to use `with` we just have to explicitly `close` the `open` call. |
| 40 | + |
| 41 | +```python |
| 42 | +file_object = open(full_path, 'r') |
| 43 | +contents = file_object.read() |
| 44 | +print(contents) |
| 45 | +contents.close() |
| 46 | +``` |
| 47 | + |
| 48 | +## 3 Download files |
| 49 | + |
| 50 | +```python |
| 51 | +def download_file(url, directory, fname=None): |
| 52 | + if fname == None: |
| 53 | + fname = os.path.basename(url) |
| 54 | + dl_path = os.path.join(directory, fname) |
| 55 | + with requests.get(url, stream=True) as r: |
| 56 | + with open(dl_path, 'wb') as f: |
| 57 | + shutil.copyfileobj(r.raw, f) |
| 58 | + return new_dl_path |
| 59 | +``` |
0 commit comments