繁体   English   中英

在其他文件夹上使用python创建文件

[英]Creating a file using python on different folder

我正在使用远程服务器,例如IP:192.128.0.3。 在此服务器上有两个文件夹: cgi-binhtml 我的python代码文件位于cgi-bin ,它想要在html/Rohith/中创建data.json文件,其中Rohith文件夹已经存在。 我使用以下代码

 jsonObj = json.dumps(main_func(s));
 fileobj = open("http://192.128.0.3/Rohith/data.json","w+");
 fileobj.write(jsonObj);

尽管我可以在python脚本的同一文件夹(cgi-bin)上创建文件,但它并未在此处创建文件。 谁能告诉我为什么它没有在给定的目的地中创建文件?

file.write不创建目录首先,您必须创建一个目录,然后使用file.write()例如

if not os.path.exists("../html/Rohith/"):
    os.makedirs("../html/Rohith/")
jsonObj = json.dumps(mainfunc(s))
fileobj = open("../html/Rohith/data.json","w+")
fileobj.write(jsonObj)

这可能是路径问题; 我建议改用完整路径。 请尝试以下操作:

import os

jsonObj = json.dumps(main_func(s));
path = '\\'.join(__file__.split('\\')[:-2])  # this will return the parent 
                                             # folder of cgi-bin on Windows
out_file = path + '/html/Ronhith/data.json'
fileobj = open(out_file, 'w+')  # w+ mode creates the file if its not exists
fileobj.write(jsonObj)

如果仍然无法正常运行,请尝试将文件模式从w+更改为a+ w+

a +打开一个文件以进行附加和读取。 如果文件存在,则文件指针位于文件的末尾。 该文件以追加模式打开。 如果该文件不存在,它将创建一个用于读取和写入的新文件。

多亏那个坐在我旁边的家伙! 当我将路径更改为本地目标而不是IP路径时,它可以工作:

fileobj = open("/var/www/html/Rohith/data.json","w+");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM