编写文件以打开选择的文件

问题描述 投票:-1回答:2

我试图写一个文件,将打开2个文本文件中的一个。我希望它弹出一个小问题,问你想要文件1或2,然后当我选择该文件时,它只是打开那个。我不认为它对我如何决定的选择感到满意。

1 = p.txt和2 = q.txt btw

def open_function (f):
    print('which file would you like? type 1 for p and 2 for q')
    choice = raw_input('> ')
    if choice == 1:
    file_choice=p.txt
    elif choice == 2:  
        file_choice=q.txt

f=open('file_choice','r')
for i in range (1):                     first_line=f.readline()
rest=f.readlines()

f.close

我一直在

File "<ipython-input-10-383b19133bad>", line 6
elif choice == 2:
   ^
SyntaxError: invalid syntax

我该怎么做才能在2之间做出选择

python function
2个回答
1
投票

你的缩进被打破了。在if之后缩小线条如下:

if choice == 1:
    file_choice = 'p.txt'
elif choice == 2:  
    file_choice = 'q.txt'

此外,您需要引用您的字符串,如图所示。


0
投票
  1. 您需要在int中指定raw_input进行比较
  2. 缩进不正确。
  3. 您需要将文件名放入引号。
  4. 您不需要打印功能..您可以将其添加到raw_input
  5. 你需要从引号中取出'file_choice`来打开文件。 def open_function (f): #print('which file would you like? type 1 for p and 2 for q') choice = int(raw_input('which file would you like? type 1 for p and 2 for q > ')) if choice == 1: file_choice='p.txt' elif choice == 2: file_choice='q.txt' f=open(file_choice,'r') for i in range (1): first_line=f.readline() rest=f.readlines() f.close
© www.soinside.com 2019 - 2024. All rights reserved.