创建一个文件夹并使用Python在该文件夹内写入文件。

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

Creating a folder and writing to a file inside that folder using python

问题

I am trying to create a new folder at the location where the python script is saved and then create a new file inside that folder and write information to it. What would be the best way to create the folder and then the path for the file? Thanks a lot.

我试图在保存Python脚本的位置创建一个新文件夹,然后在该文件夹内创建一个新文件并将信息写入其中。如何最好地创建文件夹和文件的路径?非常感谢。

I used the following code to create the folder:

我使用以下代码创建文件夹:

import os
from os import path

nameofFolder = "TestFolder"
foldercheck = os.path.isdir(nameofFolder)
if foldercheck:
    print('Folder present')
else:
    os.makedirs(nameofFolder)

I tried using the following code to create a path for the file, but that keeps creating the file in the root directory:

我尝试使用以下代码来创建文件的路径,但这会导致文件在根目录中创建:

completepath = os.path.join(nameofFolder + "/", fileName)
英文:

I am trying to create a new folder at the location where the python script is saved and then create a new file inside that folder and write information to it.
What would be the best way to create the folder and then the path for the file?
Thanks a lot.

I used the following code to create the folder

import os
from os import path

nameofFolder = "TestFolder"
foldercheck = os.path.isdir(nameofFolder)
if foldercheck:
    print('Folder present')
else:
    os.makedirs(nameofFolder)

I tried using

completepath = os.path.join(nameofFolder +"/", fileName)

to create a path for the file but that keeps creating the file in the root directory.

答案1

得分: 0

创建文件夹的代码部分:

import os

currentPath = os.getcwd()
nameofFolder = "TestFolder"

if not os.path.exists(currentPath + '/' + nameofFolder):
    os.makedirs(nameofFolder)

在文件夹内创建文件的代码部分:

fileName = "Hello"

f = open(nameofFolder + "/" + fileName, "w")

# 写入你想要的内容:
f.write(...)

f.close()

或者更方便的方式:

with open(nameofFolder + "/" + fileName, "w") as f:
   f.write(...)
英文:

To create the folder:

import os

currentPath = os.getcwd()
nameofFolder = "TestFolder"

if not os.path.exists(currentPath + '/' + nameofFolder):
    os.makedirs(nameofFolder)

To create a file inside of it:

fileName = "Hello"

f = open(nameofFolder + "/" + fileName, "w")

# writing whatever you want:
f.write(...)

f.close()

Or more conveniently:

with open(nameofFolder + "/" + fileName, "w") as f:
   f.write(...)

huangapple
  • 本文由 发表于 2023年3月9日 16:23:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75682009.html
匿名

发表评论

匿名网友

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

确定