您的位置 首页 golang

Go语言学习基础-文件路径、目录、临时文件和目录

File Path 文件路径

file path包提供了解析和构造文件路径的函数,这种方法在操作系统之间是兼容的;例如,Linux上的dir/file与Windows上的 Dir file都可以有效识别。

使用Join方法构造路径,它接受任意数量的参数来构造路径的层次结构。应该始终使用Join方法连接路径,而不是手动连接。除了提供兼容性外,Join方法还将通过删除多余的分隔符和目录规范路径。

Dir函数和Base函数可用于分割指路径为目录和文件名。函数Split则则可以同时返回两者。

我们可以检查路径是否为绝对路径。

某些文件名带有扩展名,可以使用函数Ext将扩展名从文件名中分离出来。通过删除扩展名获得文件基名,请使用strings.TrimSuffix。

函数Rel在两个目标之间查找 相对路径 ,如果没有,则返回一个错误。

Go语言学习基础-文件路径、目录、临时文件和目录

结果:

$ go run file-paths.go

p: dir1/dir2/filename

dir1/filename

dir1/filename

Dir(p): dir1/dir2

Base(p): filename

false

true

.json

config

t/file

../c/t/file

Directorie 目录

Go有几个有用的函数来处理文件系统中的目录。

函数os.Mkdir在当前工作目录中创建一个新的子目录。如果是临时目录,最好推迟删除它们,函数os.RemoveAll将删除整个目录树(类似于rm -rf)。

ioutil.WriteFile函数创建新的空文件。

我们可以创建目录层次结构,函数os.MkdirAll创建路径上的所有目录,这与命令行mkdir -p类似。

函数ioutil.ReadDir列出目录内容,返回os.FileInfo对象列表的切片。

函数os.Chdir允许我们更改当前工作目录,类似于命令行cd。

我们还可以递归地访问目录,包括所有子目录。函数filepath.Walk的 回调函数 用于处理访问的每个文件或目录,程序中filepath.Walk递归地为每个文件或目录调用visit。

Go语言学习基础-文件路径、目录、临时文件和目录

结果:

$ go run directories.go

Listing subdir/parent

child true

file2 false

file3 false

Listing subdir/parent/child

file4 false

Visiting subdir

subdir true

subdir/file1 false

subdir/parent true

subdir/parent/child true

subdir/parent/child/file4 false

subdir/parent/file2 false

subdir/parent/file3 false

Temporary File and Directorie 临时文件和目录

在程序执行过程中,我们通常希望创建一在程序退出后不需要的数据。临时文件和目录对于这个目的很有用,因为它们在程序使用过后不会污染文件系统。

创建临时文件最简单的方法是调用ioutil.TempFile,它创建并打开一个文件进行读写。第一个参数为空字符串””,因此ioutil.TempFile将在操作系统的默认位置创建临时文件。

方法Name显示临时文件的名称。

在类Unix系统,临时目录可能是/ tmp 。ioutil.TempFile的第二个参数为临时文件名的前缀,其余部分则自动产生,以确保并发创建时始终使用不同的文件名。

os.Remove推迟调用用于在使用完临时数据后清理文件。操作系统很可能会在一段时间后自行清理临时文件,但最好显式地这样做。

方法Write向文件中写入一些数据。

如果要创建许多临时文件,则可以创建一个临时目录用于放置它们。ioutil.TempDir的参数与ioutil.TempFile的参数相同,但是它返回一个目录对象,而不是文件对象。

Go语言学习基础-文件路径、目录、临时文件和目录

结果:

$ go run temporary-files-and-directories.go

Temp file name: /tmp/sample610887201

Temp dir name: /tmp/sampledir898854668

文章来源:智云一二三科技

文章标题:Go语言学习基础-文件路径、目录、临时文件和目录

文章地址:https://www.zhihuclub.com/100770.shtml

关于作者: 智云科技

热门文章

评论已关闭

40条评论

  1. It acts by inhibiting cGMP-specific phosphodiesterase type 5, an enzyme that delays degradation of cGMP, which regulates blood flow in the penis

  2. Cialis Professional tadalafil is a highly effective generic medication used to struggle against erectile dysfunction The mean apparent volume of distribution following oral administration is approximately 77 L, indicating that tadalafil is distributed into tissues

  3. Counts and proportional distributions were used to describe the categoric distributions of nominal level data

  4. erythromycin base will increase the level or effect of ambrisentan by P glycoprotein MDR1 efflux transporter 2001; Wakai et al

  5. Surat Plot No 583, Varsha Co Op Ho Society Ltd 2, Varachha Road, Matawadi, Surat 395006, Dist Belanger, et al

  6. intelligence contractor Edward Snowden has been holed up in the transit area of a Moscow airport for more than a month, despite U

  7. Structures of carmustine and lomustine demadex vitaros gel video The actor spent his 45th birthday Saturday at HollywoodГў

  8. One of the most common, simple and effective cycles of steroids include Winstrol and Testosterone Enanthate or Testosterone Cypionate

  9. 15 However, the relative contribution and importance of these processes have not been established and therefore are speculative, at best

  10. TIM50 is an important receptor for mitochondrial protein translocation, so we measured the mitochondrial morphology and biogenesis related protein level to figure out whether TIM50 influences mitochondrial dynamics In addition, the sample size may have been limited for assessing heterogeneity by tumor characteristics, and power was insufficient to conduct further subgroup analyses eg, tamoxifen use or lifestyle factors

  11. Excessive doses of Veltassa may result in hypokalemia Breast Conserving Therapy A White Paper

  12. Mierau SB, Meredith RM, Upton AL, Paulsen O 2004 Dissociation of experience dependent and independent changes in excitatory synaptic transmission during development of barrel cortex

  13. dexamethasone will decrease the level or effect of flibanserin by affecting hepatic intestinal enzyme CYP3A4 metabolism

  14. The information provided in Special warnings and precautions for use of Tamoxifen Citrate Actavis is based on data of another medicine with exactly the same composition as the Tamoxifen Citrate Actavis

  15. My husband was sick and on antibiotics a couple of times while we were doing our medicated cycles last year and he didn t show any adverse effects with any of his SAs prior to IUI

  16. There continue to be concerns regarding the continued use of clomiphene and its effect on endometrium and ovarian tumor pathogenesis

  17. Although Proviron is not approved for use in females, some females in the athletic and bodybuilding community do elect to use it

  18. There are many ways to treat or prevent osteoporosis that do not rely on drug treatment However, for use of AIs in the adjuvant setting, short term tolerability and long term effects in a healthy population are relevant

  19. Dairy products contain both hormones and growth factors, in addition to fat and various chemical contaminants, that have been implicated in the proliferation of human breast cancer cells

  20. 46, hip, wrist, or total fractures, although all rates were slightly less for raloxifene The criteria for safety and efficacy testing are much less stringent with natural supplements

  21. This methane SIBO weight gain is something that I experienced first hand, gaining over 10 kg in the space of two months before testing positive for methane SIBO and then losing it again post treatment To get the health benefits from strength exercises you should do them until you get to the point where you struggle to do any more

  22. Factors influencing prognosis Br J Cancer 30 261 271, 1974 Crossref, Medline, Google Scholar 37

  23. Arnett DK et al 2019 ACC AHA guideline on the primary prevention of cardiovascular disease a report of the American College of Cardiology American Heart Association Task Force on clinical practice guidelines

网站地图