相关疑难解决方法(0)

如何检查文件或目录是否存在?

我想./conf/app.ini在Go代码中检查文件是否存在,但我找不到一个好方法.

我知道在Java中有一个File方法:public boolean exists()如果文件或目录存在,则返回true.

但是怎么能在Go中完成呢?

file go

117
推荐指数
4
解决办法
8万
查看次数

将tilde展开到主目录

我有一个程序接受将创建文件的目标文件夹.我的程序应该能够处理绝对路径以及相对路径.我的问题是我不知道如何扩展~到主目录.

我扩展目的地的功能看起来像这样.如果给定的路径是绝对路径,则它什么也不做,否则它将与当前工作目录的相对路径连接起来.

import "path"
import "os"

// var destination *String is the user input

func expandPath() {
        if path.IsAbs(*destination) {
                return
        }
        cwd, err := os.Getwd()
        checkError(err)
        *destination = path.Join(cwd, *destination)
}
Run Code Online (Sandbox Code Playgroud)

由于path.Join不扩展~,如果用户传递类似~/Downloads目的地的东西,它就不起作用.

我该如何以跨平台的方式解决这个问题?

path go

26
推荐指数
5
解决办法
2万
查看次数

_,在Golang中意味着什么?

我是Go的新手,在浏览其他一些主题时遇到了这行代码:

if _, err := os.Stat("/path/to/whatever"); os.IsNotExist(err)
Run Code Online (Sandbox Code Playgroud)

_之后是什么意思?是否指定将在if条件中分配某些内容(因为它似乎发生在err中)?我在维基上找不到这种语法的例子,我很好奇看到它的用途.

这是我正在看的线程的链接,如果它有帮助: 如何检查Go中是否存在文件?

go

3
推荐指数
1
解决办法
2718
查看次数

如何在Go中编写安全重命名?(或者,如何在Go中编写这个Python?)

我在Python中有以下代码:

    if not os.path.exists(src): sys.exit("Does not exist: %s" % src)
    if os.path.exists(dst): sys.exit("Already exists: %s" % dst)
    os.rename(src, dst)
Run Code Online (Sandbox Code Playgroud)

这个问题,我知道没有直接的方法来测试文件是否存在或不存在.

在Go中编写上述内容的正确方法是什么,包括打印出正确的错误字符串

这是我得到的最接近的:

package main

import "fmt"
import "os"

func main() {
    src := "a"
    dst := "b"
    e := os.Rename(src, dst)
    if e != nil {
        fmt.Println(e.(*os.LinkError).Op)
        fmt.Println(e.(*os.LinkError).Old)
        fmt.Println(e.(*os.LinkError).New)
        fmt.Println(e.(*os.LinkError).Err)
    }
}
Run Code Online (Sandbox Code Playgroud)

从错误信息的可用性来看,如果没有你解析英文自由格式字符串,它实际上没有告诉你问题是什么,在我看来,不可能在Go中写出等价物.

file exists go

0
推荐指数
1
解决办法
1060
查看次数

标签 统计

go ×4

file ×2

exists ×1

path ×1