gpt4 book ai didi

python - 为什么命令行文件没有获取行?

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:27 25 4
gpt4 key购买 nike

<分区>

我最初有一个程序提示用户输入文件名 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: 之后的其余代码现在不会执行。

有什么建议吗?谢谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com