电脑上的Spyder - 无法打开文件

时间:2017-06-10 16:55:58

标签: python

请尽可能帮助。希望只是一个简单的问题。

我试图在笔记本电脑上使用python将txt文件和csv文件打开到spyder上 - microsoft pc。

尝试实施下面的代码,但它不会打开任何东西 - 我尝试了很多变化 希望你能提供帮助,非常感谢。

def print_file(filename):
    """ Opens file and prints its contents line by line. """
    infile = open(filename)

    for line in infile:
    print(line, end="")    
    infile.close()

print_file(" phones.csv&#34) 回溯(最近一次调用最后一次):

文件"",第1行,in     print_file(" phones.csv&#34)

文件"",第3行,在print_file中     infile = open(filename)

FileNotFoundError:[Errno 2]没有这样的文件或目录:' phones.csv'

另外=当我实施时!cd说它的操作文件是我的驱动器,文件在那里。

已经好几天了,所以希望你不要小心问题x

1 个答案:

答案 0 :(得分:0)

所以这里有两件事是错的。首先,您没有正确缩进for循环中的print函数调用。其次,您没有为函数提供正确的文件名。

以下是一个如何运作的示例:

正确的功能:

def print_file(filename):
    """ Opens file and prints its contents line by line. """
    infile = open(filename)

    print("Opened file, now printing it...")
    for line in infile:
        print(line, end="")
    infile.close()

我的桌面上有一个csv文件phones.csv,所以我这样称呼它:

dir = 'C:/Users/me/Desktop/'
filename = 'phones.csv'
print_file(dir + filename)

输出:

Opened file, now printing it...
123 456 1243, 423 653 6543, 234 532 5432, 543 873 6433, 975 523 5235,
453 856 5435, 423 575 5623, 742 423 9432, 523 634 8345, 421 724 5432

phones.csv的内容是

123 456 1243, 423 653 6543, 234 532 5432, 543 873 6433, 975 523 5235,
453 856 5435, 423 575 5623, 742 423 9432, 523 634 8345, 421 724 5432