Debian Codegraph @

docs/handling-files.md

raw
1 (handling-files)=
2
3 # Handling Files
4
5 ```{currentmodule} click
6 ```
7
8 Click has built in features to support file and file path handling. The examples use arguments but the same principle
9 applies to options as well.
10
11 (file-args)=
12
13 ## File Arguments
14
15 Click supports working with files with the {class}`File` type. Some notable features are:
16
17 - Support for `-` to mean a special file that refers to stdin when used for reading, and stdout when used for writing.
18 This is a common pattern for POSIX command line utilities.
19 - Deals with `str` and `bytes` correctly for all versions of Python.
20
21 Example:
22
23 ```{eval-rst}
24 .. click:example::
25
26 @click.command()
27 @click.argument('input', type=click.File('rb'))
28 @click.argument('output', type=click.File('wb'))
29 def inout(input, output):
30 """Copy contents of INPUT to OUTPUT."""
31 while True:
32 chunk = input.read(1024)
33 if not chunk:
34 break
35 output.write(chunk)
36
37 And from the command line:
38
39 .. click:run::
40
41 with isolated_filesystem():
42 invoke(inout, args=['-', 'hello.txt'], input=['hello'],
43 terminate_input=True)
44 invoke(inout, args=['hello.txt', '-'])
45 ```
46
47 ## File Path Arguments
48
49 For handling paths, the {class}`Path` type is better than a `str`. Some notable features are:
50
51 - The `exists` argument will verify whether the path exists.
52 - `readable`, `writable`, and `executable` can perform permission checks.
53 - `file_okay` and `dir_okay` allow specifying whether files/directories are accepted.
54 - Error messages are nicely formatted using {func}`format_filename` so any undecodable bytes will be printed nicely.
55
56 See {class}`Path` for all features.
57
58 Example:
59
60 ```{eval-rst}
61 .. click:example::
62
63 @click.command()
64 @click.argument('filename', type=click.Path(exists=True))
65 def touch(filename):
66 """Print FILENAME if the file exists."""
67 click.echo(click.format_filename(filename))
68
69 And from the command line:
70
71 .. click:run::
72
73 with isolated_filesystem():
74 with open('hello.txt', 'w') as f:
75 f.write('Hello World!\n')
76 invoke(touch, args=['hello.txt'])
77 println()
78 invoke(touch, args=['missing.txt'])
79 ```
80
81 ## File Opening Behaviors
82
83 The {class}`File` type attempts to be "intelligent" about when to open a file. Stdin/stdout and files opened for reading
84 will be opened immediately. This will give the user direct feedback when a file cannot be opened. Files opened for
85 writing will only be open on the first IO operation. This is done by automatically wrapping the file in a special
86 wrapper.
87
88 File open behavior can be controlled by the boolean kwarg `lazy`. If a file is opened lazily:
89
90 - A failure at first IO operation will happen by raising an {exc}`FileError`.
91 - It can help minimize resource handling confusion. If a file is opened in lazy mode, it will call
92 {meth}`LazyFile.close_intelligently` to help figure out if the file needs closing or not. This is not needed for
93 parameters, but is necessary for manually prompting. For manual prompts with the {func}`prompt` function you do not
94 know if a stream like stdout was opened (which was already open before) or a real file was opened (that needs
95 closing).
96
97 Since files opened for writing will typically empty the file, the lazy mode should only be disabled if the developer is
98 absolutely sure that this is intended behavior.
99
100 It is also possible to open files in atomic mode by passing `atomic=True`. In atomic mode, all writes go into a separate
101 file in the same folder, and upon completion, the file will be moved over to the original location. This is useful if a
102 file regularly read by other users is modified.