我很難匯入這個檔案,以便我可以使用它,任何幫助將不勝感激。
import os
path = os.path.abspath(r'C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt')
cars=open(path)
print (cars)
for line in cars:
values = line.split ()
print(values[0], 'has an MPG of', values[2], 'with', values[5])
# TODO: Split the line into a list of strings
# TODO: Print the sentence
# Close the file
cars.close()
FileNotFoundError Traceback (most recent call last)
Input In [14], in <cell line: 3>()
1 import os
2 path = os.path.abspath(r'C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt')
----> 3 cars=open(path)
4 print (cars)
6 for line in cars:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/kariwhite/Desktop/430 Python/week 4/C:Users/kariwhite/Desktop/430 Python/week 4/cars.txt'
uj5u.com熱心網友回復:
在 python 上讀取檔案時,我強烈建議使用該os.path模塊。它有助于根據您使用的作業系統組合路徑。假設您確定該檔案存在,請嘗試以下操作:
import os
pwd = os.path.join("c:/", "Users", "kariwhite","Desktop","430 Python", "week 4", "cars.txt")
with open(pwd, "r") as file:
for line in file:
values = line.split()
#...
我強烈建議也使用此處突出顯示的語法來閱讀檔案。with open() as file: ...是檔案處理的最佳實踐。
uj5u.com熱心網友回復:
如果您在用戶/kariwhite/ 中作業
嘗試
os.path.abspath(“Desktop/430 Python/week 4/cars.txt”)
如果路徑從當前作業目錄向前移動,而不是在子目錄中,您通常必須從當前作業目錄開始。
uj5u.com熱心網友回復:
請注意,os.path.abspath() 將路徑或檔案名作為代表檔案系統路徑的引數,并回傳路徑名路徑的規范化版本。
如果該檔案實際存在于指定目錄中(Users/kariwhite/Desktop/430 Python/week 4/cars.txt),并且您的作業目錄是 Users/kariwhite/Desktop/430 Python/week 4,則以下內容應該可以作業:
import os
path = os.path.abspath("cars.txt")
cars=open(path)
print (cars)
此外,如果檔案在當前作業目錄中,您可以通過直接打開檔案來使用相對路徑:
import os
cars=open("cars.txt")
print (cars)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/514427.html
