简体   繁体   English

Python无法看到csv文件

[英]Python cannot see csv file

I went through couple answers on forum already but without any success. 我已经在论坛上经历了几个答案,但没有成功。 I am using Linux mint, Python 3.6.0 and i am trying to open CSV in Python but then error occurs: 我正在使用Linux Mint,Python 3.6.0,并且尝试在Python中打开CSV,但是会出现错误:

  file = open("~/Desktop/xyz/city.csv", "rb")
FileNotFoundError: [Errno 2] No such file or directory: '~/Desktop/xyz/city.csv'

My code: 我的代码:

import csv

file = open("~/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)

I also tried to move the file to desktop as in some answers i found, instead of path i used "city.csv". 我还尝试将文件移动到桌面,如我发现的某些答案一样,而不是我使用“ city.csv”的路径。 Still doesn't work. 仍然不起作用。

Completely new to Linux and just can't find why this isn't working. Linux完全陌生,只是找不到为什么它不起作用。

Each reply appreciated! 每个答复表示赞赏!

You should'nt use '~' to specify the path of your directory but the full path instead. 您不应使用“〜”来指定目录的路径,而应使用完整路径。 Eg : 例如:

import csv

file = open("/home/user/Desktop/xyz/city.csv", "rb")
reader =csv.reader(file)

If you need to use the tilde, you should then use os.path.expanduser('~/Desktop/xyz/city.csv') . 如果需要使用波浪号,则应使用os.path.expanduser('~/Desktop/xyz/city.csv') E. g. 例如 :

import csv

file = open(os.path.expanduser("~/Desktop/xyz/city.csv"), "rb")
reader =csv.reader(file)

The reason for that is that the "tilde expansion" is a user interface feature that is not recognized by the file system: http://www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion 这样做的原因是“波浪号扩展”是文件系统无法识别的用户界面功能: http : //www.gnu.org/software/bash/manual/bashref.html#Tilde-Expansion

尝试使用完整的文件路径,如下所示:

file = open("/home/[username]/Desktop/xyz/city.csv", "rb")

Usually ~ does not expand properly. 通常~无法正常展开。 I have found that when it is needed, put $HOME environment variable value into a python variable and then use join to attach it as a prefix to the file name relative position. 我发现需要时,请将$HOME环境变量值放入python变量,然后使用join将其作为前缀附加到文件名相对位置。 This also allows you to move the file to a different location and create a function that will allow you to redefine the prefix. 这还允许您将文件移动到其他位置,并创建一个函数来重新定义前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM