code to open file:
f = open("/Desktop/temp/myfile.txt","file1")
它没有起作用。我认为这是因为我没有指定正确的路径。我该如何解决这个问题?
code to open file:
f = open("/Desktop/temp/myfile.txt","file1")
它没有起作用。我认为这是因为我没有指定正确的路径。我该如何解决这个问题?
你的代码语法有误,open
函数的使用方法不正确。
在解释器提示符下尝试以下命令:
>>> help(open)
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object.
因此,第二个参数是打开文件的模式。通过快速查看文档,我们尝试使用以下内容:
f = open("/Desktop/temp/myfile.txt","r")
编辑:哦,是的,你的第二个参数是错误的。我甚至没有注意到 :)
Python会在你指定的位置查找文件。如果你在/home/malcmcmul打开解释器,那么那里就是活动目录。
如果你指定一个路径,那么它就会在那个路径下查找文件。你确定/Desktop/temp是一个有效的路径吗?我不知道有多少设置中将/Desktop作为根文件夹。
以下是一些例子:
如果我有一个文件:/home/bartek/file1.txt
我输入python
进入目录/home/bartek/
这将正常工作并获取file1.txt:f = open("file1.txt", "r")
这将不起作用:f = open("some_other_file.txt", "r")
因为该文件在某个其他目录中。
只要我指定正确的路径,这就可以工作:f = open("/home/media/a_real_file.txt", "r")
尝试:
f = open('Desktop/temp/myfile.txt', 'r')
'/Desktop/temp/myfile.txt'
。open函数的第二个参数是模式(不知道你的示例中file1
应该是什么意思)。sys.path
。如果您想从某个子目录打开文件,请使用os.path.join,例如:import os
f = open(os.path.join('Desktop', 'temp', 'myfile.txt'), 'r')
如果您使用'/'和'\'时遇到问题,那么您可以放心了。
有关如何使用内置的open函数的更多信息,请参阅文档。
只需输入文件名,就可以找到您的数据......它是如何工作的?---->如果路径存在,则检查它是否为文件,然后打开并读取。
最初的回答:
输入文件名即可获取数据。它的功能是:检查路径是否存在,判断其是否为文件,然后打开并读取。
import os
fn=input("enter a filename: ")
if os.path.exists(fn):
if os.path.isfile(fn):
with open(fn,"r") as x:
data=x.read()
print(data)
else:
print(fn,"is not a file: ")
else:
print(fn,"file doesnt exist ")
这个:
import os
os.path
应该告诉你Python首先查找的位置。当然,如果您指定绝对路径(正如您已经做的那样),那么这就无关紧要了。
此外,正如其他人所说,您在open中的第二个参数是错误的。要找到正确的方法,请尝试使用以下代码:
help(open)
'C:\Users\20\Documents\Projects\Python\test.csv' = 不起作用
'C:/Users/20/Documents/Projects/Python/test.csv' = 完全正常工作
from pathlib import Path
import os
desired_directory = Path('C:/')
desired_directory = desired_directory / 'subfolder'
os.chdir(desired_directory)
这将迫使Python查看您指定的路径中的目录。当使用 `subprocess.Popen' 来使用二进制文件时,它非常有效,例如在此片段中:
from subprocess import Popen
from shutil import which
instance_of_Popen = Popen(which('name_of_executable'))
print(instance_of_Popen.args)