繁体   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