如何在使用子目录时修复文件访问问题?

huangapple go评论82阅读模式
英文:

How to fix file access when using a sub-directory?

问题

Go语言如何处理对目录和文件的读取访问?

我想读取一个文件夹,搜索csv文件,并将每个csv文件的内容保存起来,以便通过HTTP请求发送内容。

以下是我的代码:

func GetFileContent(fileName string) ([][]string, error) {
  file, err := os.Open(fileName)
  if err != nil {
    log.Println("There was an error:", err)
    return nil, err
  }

  defer file.Close()
  reader := csv.NewReader(file)
  reader.FieldsPerRecord = -1
  csvFileContent, err := reader.ReadAll()
  if err != nil {
    log.Println("There was an error:", err)
    return nil, err
  }
  return csvFileContent, nil
}

func GetFiles(importPath string, fileExtension string) ([]string, error) {

  var result []string

  directory, err := os.Open(importPath)
  if err != nil {
    return result, err
  }
  defer directory.Close()

  files, err := directory.Readdir(-1)
  if err != nil {
    return result, err
  }

  for _, file := range files {
    if file.Mode().IsRegular() {
      if filepath.Ext(file.Name()) == "."+fileExtension {
        log.Println("Import Files:", file.Name())
        result = append(result, file.Name())
      }
    }
  }
  if len(result) == 0 {
    log.Println("No import files of type " + fileExtension + " found.")
    log.Println("Import skipped.")
  }
  return result, nil
}

当我不使用应用程序的根目录/工作目录,而是使用另一个(父级)文件夹时,会出现"open: no such file or directory"的错误。只要我使用"./"作为源文件夹,它就能正常工作。

英文:

Which way Go does handle read access to directories and files?

I want to read a folder, search for csv files and save the content per csv file in order to send the content via http request.

Here's my code:

func GetFileContent(fileName string) ([][]string, error) {
file, err := os.Open(fileName)
if err != nil {
log.Println("There was an error:", err)
return nil, err
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = -1
csvFileContent, err := reader.ReadAll()
if err != nil {
log.Println("There was an error:", err)
return nil, err
}
return csvFileContent, nil
}
func GetFiles(importPath string, fileExtension string) ([]string, error) {
var result []string
directory, err := os.Open(importPath)
if err != nil {
return result, err
}
defer directory.Close()
files, err := directory.Readdir(-1)
if err != nil {
return result, err
}
for _, file := range files {
if file.Mode().IsRegular() {
if filepath.Ext(file.Name()) == "." + fileExtension {
log.Println("Import Files: ", file.Name())
result = append(result, file.Name())
}
}
}
if len(result) == 0 {
log.Println("No import files of type " + fileExtension + " found.")
log.Println("Import skipped.")
}
return result, nil
}

> Error: open : no such file or directory

appears when I do not use the root folder / working directory of my application but another (parent) folder? It works as long as I use ./ as source folder.

答案1

得分: 4

FileInfo.Name 返回文件的基本名称。您需要使用 join 函数将目录名称与基本名称连接起来,以获取文件路径。

在 GetFiles 函数中将以下行更改为:

result = append(result, file.Name())

更改为

result = append(result, filepath.Join(importPath, file.Name()))
英文:

FileInfo.Name returns the base name of the file. You need to join the directory name with the base name to get a file path.

Change this line in GetFiles

result = append(result, file.Name())

to

result = append(result, filepath.Join(importPath, file.Name()))

答案2

得分: 3

在这种情况下,你可以考虑使用更高级的filepath.Glob()代替:

files, err := filepath.Glob(filepath.Join(importPath, "*.csv"))
英文:

In this case, you might consider using the higher-level filepath.Glob() instead:

files, err := filepath.Glob(filepath.Join(importPath, "*.csv"))

huangapple
  • 本文由 发表于 2015年1月23日 02:00:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/28095639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定