首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么命令行文件没有得到行?

为什么命令行文件没有得到行?
EN

Stack Overflow用户
提问于 2016-02-01 19:43:17
回答 1查看 53关注 0票数 1

我最初有一个程序,它提示用户使用raw_input输入一个文件名,打开并读取该文件,并通过打印执行一些操作。

现在,我感兴趣的是从命令行参数获取文件名,如:C:\Users\MyName\pythonfile.py somenumbers.txt

当试图使用上面所见的^执行时,将打印somenumbers.txt文件,但不会对其进行进一步的操作,从行:for line in file:开始。

在提示用户使用“`raw_input”之前,我很难理解为什么可以执行进一步的操作。

下面是我以前使用的raw_input代码,可以打印出整个文件(如果我想的话),并在for line in file:之后执行所有操作。

代码语言:javascript
复制
import sys

#Query the user for a file name 
filename = raw_input("Please enter a file name: ")

integer_list = []

#Open and read the file selected by the user
#Error checking for file
#try:
    with open(filename, 'r') as file:

      #try:
        for line in file:
          if line.strip() and not line.startswith("#"):


              integer_list.append(line)


              myset = set(line.split())
              myset_count = len(myset)


              integer_list = line.split(' ')
              result = sum([int(integer_list[i]) != int(integer_list[i+1]) for i in range(len(integer_list)-1)]) + 1

              mylist = list(line.split())
              integer_list = line.split(' ')
 #finally: 
                            #file.close()   #Close the file

下面是从命令行获取文件名的代码(使用上面看到的命令行格式):

代码语言:javascript
复制
import sys
print 'here'

print 'here1'
integer_list = []
print 'here2'
print 'here3'

with open(sys.argv[1], 'r') as file:
    print(file.read())
    for line in file:
        print 'here4'
        if line.strip() and not line.startswith("#"):          
          integer_list.append(line)
          print 'here5'
          myset = set(line.split())
          myset_count = len(myset)
          print 'here6'
          integer_list = line.split(' ')
          result = sum([int(integer_list[i]) != int(integer_list[i+1]) for i in range(len(integer_list)-1)]) + 1
          mylist = list(line.split())
          integer_list = line.split(' ')

我现在可以用涉及命令行的代码输入以下内容:

代码语言:javascript
复制
    here
    here1
    here2
    here3
    This is the file data 
    This is more of the file

我感到困惑的是,为什么for line in file:之后的其余代码现在不会执行。

有什么建议吗?谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-01 19:47:09

代码语言:javascript
复制
print(file.read())
for line in file:
    ...

使用file.read(),您已经阅读了所有内容:您现在处于文件的末尾。

从文件的末尾开始,没有更多的行要读取,因此for line in file不会运行,因为file已经耗尽。

要么删除print(file.read())行,要么倒带文件:

代码语言:javascript
复制
print(file.read())
file.seek(0, os.SEEK_SET)
for line in file:
    ...
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35138945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档