Golang имя файла без расширения
This package is not in the latest version of its module.
Repository
ianlancetaylor commented Dec 10, 2019
Although the compiler made a different choice, for the standard library we've historically preferred all lowercase just to avoid confusion on case-insensitive systems. I don't know that this is written down anywhere. I don't know that we have any particular guidance for file names in packages outside the standard library.
dmitshur added the NeedsDecision Feedback is required from experts, contributors, and/or the community before a change can be made. label Dec 14, 2019
Index ¶
Examples ¶
dmitshur commented Dec 9, 2019 •
The Go project itself tends to prefer short names like io.go , pipe.go , etc. In the rare cases two words are needed, they are joined without an underscore, like cputicks.go or debugcall.go . For more complicated packages with many files, underscores are sometimes used when additional separation is needed.
Variables ¶
Discard is an io.Writer on which all Write calls succeed without doing anything.
As of Go 1.16, this value is simply io.Discard.
Repository
dmitshur commented Dec 14, 2019 •
I don't know that we have any particular guidance for file names in packages outside the standard library.
At this time, I'm inclined to believe we should not.
People who care about this can look at the .go file naming strategies used by the Go standard library and mimic it. Those who don't care can choose a naming strategy that they prefer.
othell-sr commented Oct 31, 2021
It may be a good safeguard to have filename go through filepath.Base() first
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Documentation NeedsDecision Feedback is required from experts, contributors, and/or the community before a change can be made.
chmike commented Sep 22, 2021
@missinglink My understanding and assumption is that the file extension is the letter sequence after the last point. A file name may contain dots (.e.g start with a dot).
The file extension .tar.gz should be .tgz.
Comments
carnott-snap commented Dec 10, 2019 •
That is useful to note. It led me down a bit of a rabbit hole, and it looks like even the standard library is not consistent (though lowercasealloneword seems to be in the plurality). Should we make a standard?
file.extension.go
snake_case.go
lowercase.go
CamelCase.go
missinglink commented Sep 22, 2021
@chmike what about filenames with multiple periods like 'foo.tar.gz'?
strings.LastIndexByte will return 'foo.tar' when you probably want 'foo'?
Functions ¶
func Abs ¶
Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique. Abs calls Clean on the result.
func Base ¶
Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns ".". If the path consists entirely of separators, Base returns a single separator.
Share Format Run
func Clean ¶
Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:
The returned path ends in a slash only if it represents a root directory, such as "/" on Unix or `C:\` on Windows.
Finally, any occurrences of slash are replaced by Separator.
If the result of this process is an empty string, Clean returns the string ".".
func Dir ¶
Dir returns all but the last element of path, typically the path's directory. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns ".". If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory.
Share Format Run
func EvalSymlinks ¶
EvalSymlinks returns the path name after the evaluation of any symbolic links. If path is relative the result will be relative to the current directory, unless one of the components is an absolute symbolic link. EvalSymlinks calls Clean on the result.
func Ext ¶
Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.
Share Format Run
func FromSlash ¶
FromSlash returns the result of replacing each slash ('/') character in path with a separator character. Multiple slashes are replaced by multiple separators.
func Glob ¶
Glob returns the names of all files matching pattern or nil if there is no matching file. The syntax of patterns is the same as in Match. The pattern may describe hierarchical names such as /usr/*/bin/ed (assuming the Separator is '/').
Glob ignores file system errors such as I/O errors reading directories. The only possible returned error is ErrBadPattern, when pattern is malformed.
func HasPrefix deprecated
HasPrefix exists for historical compatibility and should not be used.
Deprecated: HasPrefix does not respect path boundaries and does not ignore case when required.
func IsAbs ¶
IsAbs reports whether the path is absolute.
Share Format Run
func Join ¶
Join joins any number of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string. On Windows, the result will only be a UNC path if the first non-empty element is a UNC path.
Share Format Run
func Match ¶
Match reports whether name matches the shell file name pattern. The pattern syntax is:
Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.
On Windows, escaping is disabled. Instead, '\\' is treated as path separator.
Share Format Run
func Rel ¶
Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can't be made relative to basepath or if knowing the current working directory would be necessary to compute it. Rel calls Clean on the result.
Share Format Run
func Split ¶
Split splits path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.
Share Format Run
func SplitList ¶
SplitList splits a list of paths joined by the OS-specific ListSeparator, usually found in PATH or GOPATH environment variables. Unlike strings.Split, SplitList returns an empty slice when passed an empty string.
Share Format Run
func ToSlash ¶
ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes.
func VolumeName ¶
VolumeName returns leading volume name. Given "C:\foo\bar" it returns "C:" on Windows. Given "\\host\share\foo" it returns "\\host\share". On other platforms it returns "".
func Walk ¶
Walk walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.
All errors that arise visiting files and directories are filtered by fn: see the WalkFunc documentation for details.
The files are walked in lexical order, which makes the output deterministic but requires Walk to read an entire directory into memory before proceeding to walk that directory.
Walk does not follow symbolic links.
Walk is less efficient than WalkDir, introduced in Go 1.16, which avoids calling os.Lstat on every visited file or directory.
Share Format Run
func WalkDir ¶ added in go1.16
WalkDir walks the file tree rooted at root, calling fn for each file or directory in the tree, including root.
All errors that arise visiting files and directories are filtered by fn: see the fs.WalkDirFunc documentation for details.
The files are walked in lexical order, which makes the output deterministic but requires WalkDir to read an entire directory into memory before proceeding to walk that directory.
WalkDir does not follow symbolic links.
Details
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Modules with tagged versions give importers more predictable builds.
When a project reaches major version v1 it is considered stable.
carnott-snap commented Dec 9, 2019
If I have simply missed where this is documented, please let me know where I should have looked, and close this out.
Many places describe how custom filename suffixes interact with the toolchain: _test , _linux , _arm . However I cannot find anywhere that says you should use snake case for multi-word file names, as is suggested by the standard library: e.g. time/zoneinfo_read.go / os/removeall_at.go not time/zoneinfoRead.go / os/removeallAt.go or time/zoneinfo-read.go / os/removeall-at.go .
This may seem self evident to experienced users, but I have seen many people get confused by the fact that variables use CamelCase := "" , while files use snake_case.go .
The text was updated successfully, but these errors were encountered:
Index ¶
Examples ¶
Constants ¶
Documentation ¶
eslindsey commented Sep 17, 2020
TrimSuffix performs a check to make sure the suffix matches before removal. Since this is a guarantee because you are using the source string's own extension, I think this could be more efficiently written using slice notation:
return fileName[:len(fileName) - len(filepath.Ext(fileName))]
One could argue that yours is more easy to read.
Overview ¶
Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
The filepath package uses either forward slashes or backslashes, depending on the operating system. To process paths such as URLs that always use forward slashes regardless of the operating system, see the path package.
peterbourgon commented Jan 30, 2020 •
There is a de facto standard for Go source file names: all lowercase with underscore separation when necessary, i.e. snake case. (The exceptions are exceptions.) I'd appreciate having it as a documented standard, too, to answer questions like @carnott-snap notes, especially among junior Gophers. In my opinion it needn't be so formal as entering Effective Go, a short new section on CodeReviewComments is more than sufficient.
File names
Go source file names should be lowercase_with_underscores.go and not camelCase.go or TitleCase.go. This makes them consistent with other language conventions, like _test.go for test files, or _windows.go for build constraints. It also prevents ambiguities on case-insensitive file systems.
This package is not in the latest version of its module.
Variables ¶
ErrBadPattern indicates a pattern was malformed.
SkipDir is used as a return value from WalkFuncs to indicate that the directory named in the call is to be skipped. It is not returned as an error by any function.
carnott-snap commented Dec 17, 2019
I opened this issue because I have colleagues that asked, what filename conventions should I use with go?
I can understand that trying to stabilise this now may be problematic, noisy, or too late. But the lack of consensus will cause some amount of confusion and cognitive overhead. Because the community (seems to) understand the benefits of standardisation, see gofmt , even a soft recommendation in a blog post would go a long way.
Documentation ¶
Constants ¶
This section is empty.
chmike commented May 6, 2021
This is probably more efficient and straightforward.
eslindsey commented Sep 22, 2021
@missinglink if I were writing software to handle gzipped files, then it should properly find the name to be foo.tar after removing its .gz extension, so yes the function should return foo.tar . Also, what about users that make files like Footage from 04.04.83.mp4 ? Presumably you don't want this function returning Footage from 04 . Extension should always be logically construed to mean "the last extension."
@chmike I hate .tgz because tar and gzip are two different things. Bothers my OCD, and my ability to find all the gzipped files in a directory. 😂 Two extensions totally makes sense to me in this case.
missinglink commented Sep 22, 2021
ok fair enough, filepath.Ext() agrees:
The extension is the suffix beginning at the final dot in the final element of path
Bash has a few different ways of getting the extension, depending on what you want:
Details
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Modules with tagged versions give importers more predictable builds.
When a project reaches major version v1 it is considered stable.
Functions ¶
func NopCloser ¶
NopCloser returns a ReadCloser with a no-op Close method wrapping the provided Reader r.
As of Go 1.16, this function simply calls io.NopCloser.
func ReadAll ¶
ReadAll reads from r until an error or EOF and returns the data it read. A successful call returns err == nil, not err == EOF. Because ReadAll is defined to read from src until EOF, it does not treat an EOF from Read as an error to be reported.
As of Go 1.16, this function simply calls io.ReadAll.
Share Format Run
func ReadDir ¶
ReadDir reads the directory named by dirname and returns a list of fs.FileInfo for the directory's contents, sorted by filename. If an error occurs reading the directory, ReadDir returns no directory entries along with the error.
As of Go 1.16, os.ReadDir is a more efficient and correct choice: it returns a list of fs.DirEntry instead of fs.FileInfo, and it returns partial results in the case of an error midway through reading a directory.
Share Format Run
func ReadFile ¶
ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.
As of Go 1.16, this function simply calls os.ReadFile.
Share Format Run
func TempDir ¶
TempDir creates a new temporary directory in the directory dir. The directory name is generated by taking pattern and applying a random string to the end. If pattern includes a "*", the random string replaces the last "*". TempDir returns the name of the new directory. If dir is the empty string, TempDir uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempDir simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when no longer needed.
As of Go 1.17, this function simply calls os.MkdirTemp.
Share Format Run
Share Format Run
func TempFile ¶
TempFile creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting *os.File. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". If dir is the empty string, TempFile uses the default directory for temporary files (see os.TempDir). Multiple programs calling TempFile simultaneously will not choose the same file. The caller can use f.Name() to find the pathname of the file. It is the caller's responsibility to remove the file when no longer needed.
As of Go 1.17, this function simply calls os.CreateTemp.
Share Format Run
Share Format Run
func WriteFile ¶
WriteFile writes data to a file named by filename. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.
If you want to grab the name of a file without its extension, you can take a slice of the complete string as shown below:
In this case, the extension length is subtracted from the length of the full string and the result is used to create a substring that excludes the extension.
Another way is to use the strings.TrimSuffix method to remove the trailing suffix string specified in its second argument:
This method is a arguably more readable than the previous one, but it’s also slower because TrimSuffix needs to make sure the suffix matches before removal. Here’s a benchmark that shows how the slice notation method is approximately twice as fast as the trim suffix method:
Thanks for reading, and happy coding!
About the Author
Ayo is a Software Developer by trade. He enjoys writing about diverse technologies in web development, mainly in Go and JavaScript/TypeScript.
Learn more.
Recent projects
Bi-weekly newsletter
How to process file uploads in Go
This article will teach you how you can upload single or multiple files to a Golang web server, and show progress reporting on file uploads
How to work with Data Types in Go
This article will take you through the various basic data types in Go, the operations that can be done on these types, and how to convert …
Working with Variables in Go
In this article, we'll cover some variable basics and best practices for using them within Go programs.
Support the Freshman blog
Lots of time and effort goes into creating all the content on this website. If you enjoy my work, consider supporting what I do through a financial donation. You can support the Freshman blog with a one-time or monthly donation through one of the following channels:
Comments
Ground rules
Please keep your comments relevant to the topic, and respectful. I reserve the right to delete any comments that violate this rule. Feel free to request clarification, ask questions or submit feedback.
About me
I'm Ayo, a Software Developer by trade. I have a keen interest in a variety of topics such as Web performance, TypeScript, and the Go programming language. In my spare time, I enjoy sports , books and photography .
Freshman is my personal tech blog where I share articles, tutorials, and tips on diverse topics across the software development landscape. If you enjoy the content on this blog, subscribe to my bi-weekly email newsletter and consider supporting the blog to keep it going.
©2016-2022 Ayooluwa Isaiah. All rights reserved. Code snippets may be used freely under the terms of the MIT Licence.
Latest side project
Focus is a cross-platform productivity timer for the command line. It is based on the Pomodoro Technique, a time management method developed by Francesco Cirillo in the late 1980s.
Types ¶
type WalkFunc ¶
WalkFunc is the type of the function called by Walk to visit each file or directory.
The path argument contains the argument to Walk as a prefix. That is, if Walk is called with root argument "dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a".
The directory and file are joined with Join, which may clean the directory name: if Walk is called with the root argument "x/../dir" and finds a file named "a" in that directory, the walk function will be called with argument "dir/a", not "x/../dir/a".
The info argument is the fs.FileInfo for the named path.
The error result returned by the function controls how Walk continues. If the function returns the special value SkipDir, Walk skips the current directory (path if info.IsDir() is true, otherwise path's parent directory). Otherwise, if the function returns a non-nil error, Walk stops entirely and returns that error.
The err argument reports an error related to path, signaling that Walk will not walk into that directory. The function can decide how to handle that error; as described earlier, returning the error will cause Walk to stop walking the entire tree.
Walk calls the function with a non-nil err argument in two cases.
First, if an os.Lstat on the root directory or any directory or file in the tree fails, Walk calls the function with path set to that directory or file's path, info set to nil, and err set to the error from os.Lstat.
Second, if a directory's Readdirnames method fails, Walk calls the function with path set to the directory's path, info, set to an fs.FileInfo describing the directory, and err set to the error from Readdirnames.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
package main |
import ( |
"strings" |
"path/filepath" |
) |
func fileNameWithoutExtension ( fileName string ) string |
return strings . TrimSuffix ( fileName , filepath . Ext ( fileName )) |
> |
Overview ¶
Package ioutil implements some I/O utility functions.
As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details.
Читайте также: