簡體   English   中英

沒有使用 Python 的此類文件或目錄

[英]No such file or directory using Python

我正在嘗試用 python 編寫一個程序,它從文件中讀取用戶名列表,並向 Instagram 發送請求以查看用戶名是否可用。 然后它應該提示一條消息,說“此用戶名可用”或“此用戶名已被占用”。 嘗試讀取我的文件時出現錯誤,指出“FileNotFoundError: [Errno 2] 沒有這樣的文件或目錄:“list.txt”,即使該文件位於我的程序所在的文件夾中。

我對python也很陌生。

這是我目前的代碼:

import requests
filepath = 'list.txt'
separator = "\n" #Every time you use a newline it detects it as a new user
list  = open(filepath, "r").read().split(separator)
notTaken = []
for i in list :
    response = requests.get("https://instagram.com/" + i + "/")
    if response.status_code == 404 :
        notTaken.append(i)

它在我的情況下有效。 我的list.txt與我的 python 文件在同一目錄中

import requests
with open('list.txt','r') as f:
    data = f.read().split("\n")

for i in data:
    pass
    #...(write the rest of the code)

使用該文件的絕對目錄,即/home/directory/file_name如果您正在使用 window 否則使用c:\\\\\\\\directory\\\\file_name這是如果文件不在終端的當前工作目錄中。 如果你在終端中文件的同一目錄下,使用./file_name

由於該文件與您的程序位於同一目錄中,因此您的代碼僅在當前工作目錄也是同一目錄時才有效。 如果你想從任何地方運行這個程序,你需要一種方法來找到那個目錄。

當 python 執行腳本或模塊時,它會添加一個__file__變量來給出路徑。 (擴展模塊和壓縮包中的模塊可能沒有這個變量)。 __file__路徑可以相對於當前工作目錄或絕對路徑。 pathlib庫為我們提供了一種處理路徑的便捷方法。 所以,

from pathlib import Path
separator = "\n" #Every time you use a newline it detects it as a new user
filename = 'list.txt'
# get absolute path, then parent directory, then add my file name
filepath = Path(__file__).resolve().parent/filename
mylist = filepath.open().read().split(separator)

由於使用"\\n"換行符來分隔文件,因此您無需自行拆分。 你可以這樣做

mylist = filepath.open().readlines()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM