Go's standard library does not have a function solely intended to check if a file exists or not (like Python's os.path.exists
). What is the idiomatic way to do it?
相关问题
- What is the best way to do a search in a large fil
- Spring Integration - Inbound file endpoint. How to
- Golang mongodb aggregation
- How to flatten out a nested json structure in go
- how to install private repo using glide golang
相关文章
- Can I run a single test in a suite?
- How to check if a request was cancelled
- What is the correct way to declare and use a FILE
- Is it possible to implement an interface with unex
- Making new files automatically executable?
- How to access value of first index of array in Go
- Embedded Interface
- How to serialize data into indented json [duplicat
You should use the
os.Stat()
andos.IsNotExist()
functions as in the following example:The example is extracted from here.
To check if a file doesn't exist, equivalent to Python's
if not os.path.exists(filename)
:To check if a file exists, equivalent to Python's
if os.path.exists(filename)
:Answer by Caleb Spare posted in gonuts mailing list.
Taken from: https://groups.google.com/forum/#!msg/golang-nuts/Ayx-BMNdMFo/4rL8FFHr8v4J
The example by user11617 is incorrect; it will report that the file exists even in cases where it does not, but there was an error of some other sort.
The signature should be Exists(string) (bool, error). And then, as it happens, the call sites are no better.
The code he wrote would better as:
But I suggest this instead:
The function example: