簡體   English   中英

我正在嘗試從其他目錄讀取python中文本文件的內容-找不到文件錯誤

[英]I'm trying to read contents of text file in python from a different directory - get file not found error

這是我的代碼:

# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 22:06:43 2019

@author: Om
"""

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime
from datetime import timedelta

# Define the symbol list
symbol = []
# Select file to access
filename=input('Enter the name of file to access')
filename=filename+'.txt'
print(filename)

with open('D:\\om\\python_stock_script\\filename')as f:
    for line in f:
        symbol.append(line.strip())
f.close

我收到以下錯誤:

Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.6.1 -- An enhanced Interactive Python.

runfile('D:/Om/python_stock_script/StockEval.py', wdir='D:/Om/python_stock_script')

Enter the name of file to accessDivStock
DivStock.txt
Traceback (most recent call last):

  File "<ipython-input-1-95059502a977>", line 1, in <module>
    runfile('D:/Om/python_stock_script/StockEval.py', wdir='D:/Om/python_stock_script')

  File "C:\Users\Om\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\Om\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "D:/Om/python_stock_script/StockEval.py", line 22, in <module>
    with open('D:\\om\\python_stock_script\\filename')as f:

FileNotFoundError: [Errno 2] No such file or directory: 'D:\\om\\python_stock_script\\filename'

如果替換文件名“ DivStock.txt”,則該代碼有效。 該文件存在於指定目錄中,因為我將其放置在該目錄中。 我嘗試了幾種方法,包括“ pathlib”。 顯然我做錯了。 我希望能夠選擇要選擇的文件。 請幫忙

在您的代碼中,您正在打開一個靜態名稱為“ filename”的文件。 除非該文件存在於該目錄中(文件名為:“文件名”),否則您將得到一個錯誤。

with open('D:\\om\\python_stock_script\\filename')as f:

我假設您要執行的操作是在該文件目錄的末尾插入您之前輸入的文件名。 現在您還沒有這樣做,您所要做的就是將靜態路徑放置到名為“ filename”的文件中。 如果您確實希望將“文件名”替換為變量,則必須使用一些字符串插值法。 這是一種簡單的方法:

with open(f"D:\\om\\python_stock_script\\{filename}")as f:

通過將f放在引號之前,您可以讓python知道您將在該字符串中混入變量。 為了將變量與字符串的其余部分區分開,將其封裝在花括號中。 這應該已經可以正常工作,但是如果您想對其進行一些清理,可以通過在字符串前面放置一個“ r”並使用單反斜杠來消除雙反斜杠。

with open(rf"D:\om\python_stock_script\{filename}")as f:

另外,您不需要以下行:

f.close

不要誤會我的意思,如果您使用f.open()主持它,那么這很重要,在這種情況下,不關閉文件可能會導致問題。 但是,由於您將with open() as f: :,所以沒有必要,因為一旦退出with塊,python就會自動關閉文件。

希望有幫助!

您傳遞給open方法的字符串已損壞。 您要將變量名filename包含在字符串中。 一種方法是:

with open('D:\\om\\python_stock_script\\'+filename)as f:

如果您想了解更多信息,請閱讀有關字符串連接的信息。

暫無
暫無

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

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