我最初有一个程序,它提示用户使用raw_input输入一个文件名,打开并读取该文件,并通过打印执行一些操作。
现在,我感兴趣的是从命令行参数获取文件名,如:C:\Users\MyName\pythonfile.py somenumbers.txt
当试图使用上面所见的^执行时,将打印somenumbers.txt文件,但不会对其进行进一步的操作,从行:for line in file:开始。
在提示用户使用“`raw_input”之前,我很难理解为什么可以执行进一步的操作。
下面是我以前使用的raw_input代码,可以打印出整个文件(如果我想的话),并在for line in file:之后执行所有操作。
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下面是从命令行获取文件名的代码(使用上面看到的命令行格式):
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(' ')我现在可以用涉及命令行的代码输入以下内容:
    here
    here1
    here2
    here3
    This is the file data 
    This is more of the file我感到困惑的是,为什么for line in file:之后的其余代码现在不会执行。
有什么建议吗?谢谢。
发布于 2016-02-01 19:47:09
print(file.read())
for line in file:
    ...使用file.read(),您已经阅读了所有内容:您现在处于文件的末尾。
从文件的末尾开始,没有更多的行要读取,因此for line in file不会运行,因为file已经耗尽。
要么删除print(file.read())行,要么倒带文件:
print(file.read())
file.seek(0, os.SEEK_SET)
for line in file:
    ...https://stackoverflow.com/questions/35138945
复制相似问题