简体   繁体   English

Python从文件输出内容

[英]Python outputting contents from file

When I'm running the program it is outputting that no countries exist starting with that letter, when in fact they exist. 当我运行该程序时,它输出的是从该字母开始就没有国家存在,而实际上它们存在。 Can someone tell me what I'm doing wrong or maybe give me an alternate way to only output countries starting with the wanted letter. 有人可以告诉我我做错了什么,或者可以给我一个替代方法,只输出以通缉信开头的国家。 This is my code: 这是我的代码:

#Creating the list
CountryList = []
CountryandPopulationList = []
#Creating the Function1
def Function1(fh,letter):
    count = 0
    #Adding the file to the list
    for word in fh:
        CountryandPopulationList.append(word)
        index = word.find('-')
        Country = word[0:index]
        CountryList.append(Country.strip()) 

    #Printing countries starting with chosen letter
    try:
        for i in CountryList:
            if(i[1]== letter):
                print(i)
                count = count + 1
            else:
                print('The letter does not exist')
    except IndexError:
        print('Total number of countries starting with letter',letter,'=',count )

#Asking user to input letter
letter = input('Enter the first letter of the country: ')

#Opening the file 
try:
    fh = open('D:\FOS\\Countries.txt','r')
except IOError:
    print('File does not exist')
else:
    function1 = Function1(fh,letter)

Thank you 谢谢

Please also provide the input format of your Countries.txt file as well as the python version you are using st it is easier to help you. 还请提供您的Countries.txt文件的输入格式以及您正在使用的python版本,这样更容易为您提供帮助。

For a start: open() will not provide you with the file content but only gives you the textwrapper object. 首先:open()不会为您提供文件内容,但只提供textwrapper对象。 Try changing the line to 尝试将线路更改为

fh = open('D:\FOS\...\Countries.txt', 'r').read()

A slightly simpler version. 一个稍微简单的版本。 Try this: 尝试这个:

def function1(fh, letter):
    count = 0
    country_list = [line.split('-')[0].strip() for line in fh.readlines()]

    for country in country_list:
        if country.lower().startswith(letter.lower()):
            count += 1
            print(country)
    print("Total number of countries starting with letter '%s'= %d" % (letter, count))


#Asking user to input letter
letter = input('Enter the first letter of the country: ')

#Opening the file
try:
    with open('D:\FOS\\Countries.txt','r') as fh:
        function1(fh, letter)
except IOError:
    print('File does not exist')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM