【问题标题】:How can i read a file as relative path in Python with Visual Studio Code?如何使用 Visual Studio Code 在 Python 中将文件作为相对路径读取?
【发布时间】:2018-12-16 02:57:01
【问题描述】:

Visual Studio Code 中以 相对路径 读取文件时发生文件未找到错误。 该文件当前与 python 脚本位于同一文件夹中。 通过在 Visual Studio 中运行相同的脚本可以成功读取。

如何修复它,以便在 Visual Studio Code 中将文件作为相对路径读取?

这是我的python脚本:

import numpy as np
file_name = 'file.csv'
xy = np.loadtxt(file_name, delimiter=',') # File not found error occured in Visual Studio Code

我的操作系统是 Windows。

【问题讨论】:

  • 你用的是哪个python? python 2 还是 python 3?
  • 这是“将文件作为相对路径读取”的正确代码。显然,您还需要了解路径是相对的(这取决于您如何启动该代码)......所以并不完全清楚您在问什么。
  • @huynhsamha 这是 Python 3 (3.5.2)
  • @AlexeiLevenkov 我按你说的改了^^
  • @hyunjin-Kim 你的代码仍然可以工作,请再试一次imgur.com/ZZdqN3n

标签: python windows visual-studio-code


【解决方案1】:

os 模块用于文件路径总是安全的。以下代码打印当前目录和file.csv 的完整路径(如果该目录中存在)。

import os
cwd = os.getcwd()  # get current working dir: C:\\Users\\%USERPROFILE%\\Desktop
print("My current working directory is: {} ".format(cwd))
#search if the file exists in this directory
for file in os.listdir(cwd):
    if file.startswith("file"):
        print("File \"{}\" is located at \"{}\"".format(file, os.path.join(cwd, file)))

如果在目录中找到该文件,请使用完整路径并将其作为原始字符串或使用os.path.join() 存储在变量中。例如:

file_name = r"C:\Users\%USERPROFILE%\Desktop\file.csv" #raw string

file_name = os.path.join(cwd, "file.csv") #join current working directory with the file.csv

两者都将完整路径显示为C:\\Users\\%USERPROFILE%\\Desktop\\file.csv

要打印目录中的所有 csv 文件(及其路径),请使用 file.endswith(".csv")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2017-03-17
    • 1970-01-01
    相关资源
    最近更新 更多