当使用文件的绝对路径时,我无法在python中写入文件

2024-10-02 00:44:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个脚本,用于在python中写入文件:

a_file = open("file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")
a_file.write("hello")

文件的绝对路径为:file:///C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt

但是,程序不会写入(追加)文件。我可以运行程序,但文件没有任何变化。奇怪的是,如果我将文件放在与脚本相同的目录中,并使用位置“testfiletrytoverwriteme.txt”运行脚本,它就会工作。即:

a_file= open("testfileTryToOVERWRITEME.txt", "a+")

a_file.write("hello")

这可以100%工作并附加到文件中。但是当我使用文件的绝对路径时,它永远不会工作。怎么了

编辑 我什么都试过了,但还是不行

我的代码:

a_file= open("C://Users//xdo//OneDrive//Desktop//Javascript//read%20and%20write//testfileTryToOVERWRITEME.txt", "a+")

a_file.write("hello")
a_file.close()

这不起作用。我还尝试:

a_file= open("C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt", "a+")

a_file.write("hello")
a_file.close()

这不起作用

编辑(最终生效)

它终于起作用了。我将“%20”替换为常规空格“”,并使用pathlib模块,如下所示:

from pathlib import Path
filename = Path("C:/Users/qqWha/OneDrive/Desktop/Javascript/read and write/testfileTryToOVERWRITEME.txt")
f = open(filename, 'a+')
f.write("Hello")

现在它写入文件。 它还可以使用“with”。像这样:

with open("c:/users/xdo/OneDrive/Desktop/Javascript/read and write/testfileTryToOVERWRITEME.txt", "a+") as file:
file.write("hello")

Tags: 文件程序txt脚本编辑helloonedriveopen
2条回答

试着做“与”。另外,将%20替换为空格。Python不会自动对此进行解码,但在下面的实例中使用空格不应该有问题

with open("c:/users/xdo/OneDrive/Desktop/Javascript/read and write/testfile.txt", "a+") as file:
    file.write("hello")

在这种情况下,如果文件不存在,它将创建它。唯一能阻止这种情况的是,如果存在权限问题

这会奏效的。当我们使用open函数在python中打开文件时,我们必须使用两个正斜杠

f = open('C://Users//xdo//OneDrive//Desktop//Javascript//read%20and%20write//testfileTryToOVERWRITEME.txt', 'a+')
f.write("writing some text")
f.close()

或者,您可以使用另一种方式来使用from pathlib import Path

from pathlib import Path
filename = Path("C:/Users/xdo/OneDrive/Desktop/Javascript/read%20and%20write/testfileTryToOVERWRITEME.txt")
f = open(filename, 'a+')
f.write("Hello")
f.close()

如果仍然存在问题,请尝试另一种绝对路径,如"C:/Users/xdo/OneDrive/Desktop/testfileTryToOVERWRITEME.txt"

相关问题 更多 >

    热门问题