使用os模块在目录中创建文件无法正常工作。

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

creating a file inside a directory with os module doesn't work

问题

所以我尝试从运行这段代码在我的目录中创建一个文件

```python
cur_directory = os.getcwd()
file1 = 'first.txt'
combined = os.path.join(cur_directory, file1)
print(combined)
print(os.path.exists(combined))

当我运行它时,我的终端显示如下:
C:\Users.....\OsModule\first.txt
False

但是在实际情况下,当我打开Osmodule目录时,first.txt 似乎不存在
这就是为什么它返回 'False' 的原因

我添加了这一行来查看是否有任何隐藏的问题,但看起来文件不存在,因为它返回 'False'

print(os.path.exists(combined))
英文:

so im trying to create a file inside my directory from running this code

cur_directory = os.getcwd()
file1 = 'first.txt'
combined = os.path.join(cur_directory, file1)
print(combined)
print(os.path.exists(combined))

well when i run it i get this on my terminal
C:\Users.....\OsModule\first.txt
False

but in the real time when i open the Osmodule directory the first.txt seems to be non existant
and that's why it returns False

i added this to see if there was any kind of hidden problems but it looks like it the file is non existant as it returns 'False'

print(os.path.exists(combined))

答案1

得分: 0

使用Open()创建一个文件。

with open('first.txt', 'w') as f:
    print('first.txt已创建')
英文:

Use Open() to Create a file.

with open('first.txt', 'w') as f:
print('first.txt created')

答案2

得分: 0

你实际上并没有写入文件。

with open(os.path.join(path, file), 'w') as fp:
    pass
英文:

You're actually not writing the file.

with open(os.path.join(path, file), 'w') as fp:
    pass

huangapple
  • 本文由 发表于 2023年7月13日 20:51:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679576.html
匿名

发表评论

匿名网友

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

确定