0

我是 python 新手,正在尝试编写一个可以打开文件并选择最大数字的函数。我在打开文件以首先读取时遇到问题。当我将代码复制并粘贴到 shell 时,它会完美地打开文件,但在函数内部它一直说找不到文件。该文件位于当前 shell 目录中 - 我是否需要编辑函数以重定向 shell?

def choose_biggest(file_0):
    with open("file_0", "r") as f:
        for line in f:
            print(' '.join(sorted(line.split())))
    pass

我还没有完成,但这是到目前为止的代码。

4

3 回答 3

2

换线

with open("file_0", "r") as f:

with open(file_0, "r") as f:
于 2013-11-02T18:16:31.980 回答
2
def choose_biggest(file_0):
    with open(file_0, "r") as f:
        for line in f:
            print(' '.join(sorted(line.split())))

你不需要引用变量

于 2013-11-02T18:17:07.770 回答
1
def choose_biggest(file_0):
    with open(file_0, "r") as f:
        for line in f:
            print(' '.join(sorted(line.split())))

The first argument in open() is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it's omitted.

于 2013-11-02T18:23:13.123 回答