Python程序无法在文件中读取

时间:2015-06-29 15:46:45

标签: python python-3.x

尝试创建一个简单的程序,计算文件中的行数,单词数和字符数。我似乎无法读取文件,它返回文件的名称而不是文件的内容。我一直在命令行中传递文件名而没有引号。

print("This program will count the number of line, words, and characters in a file.")
user_in = input("Please enter a file to be counted: ")
infile = open(user_in, "r")


lc = 0
wc = 0
w_len = 0


for line in infile:
    usr_list = user_in.split(" ")
    print(usr_list)
    lc += 1
    for x in usr_list:
        w_len += len(x)
        wc += 1

#avg = w_len//wc
print("There were {} lines, {} words, and {} characters in your file.".format(lc, wc, w_len))

infile.close()

2 个答案:

答案 0 :(得分:1)

你正在做usr_list = user_in.split(" "),但似乎你想做usr_list = line.split(" ")

答案 1 :(得分:1)

这一行:

{"installed":{"client_id":"clientid","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://accounts.google.com/o/oauth2/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_email":"","client_x509_cert_url":"","client_secret":"mysecret","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://mysite.de"]}}

分割文件的名称,而不是从文件中读取的行。

你应该做的是:

usr_list = user_in.split(" ")