【问题标题】:Can anyone help me figure out how to import this .txt file into my code?谁能帮我弄清楚如何将此 .txt 文件导入我的代码中?
【发布时间】:2019-11-30 23:28:09
【问题描述】:

我正在 VS 中的 Github 存储库中工作。我将这个stats.csv 文件导入到我的代码中,但.readlines() 调用没有打印任何内容。有谁知道为什么?谢谢

尝试了许多不同的导入方法

#this is our main code
import os

cmd = 'curl https://raw.githubusercontent.com/ksu-is/NFLQuarterbackstatIdentifier/master/stats.csv -o stats.txt'

os.system(cmd)

stats = open('stats.txt', 'a+')
statheadings = stats.readlines()

print(statheadings)
print("123123")

应该打印stats.csv 文件行

【问题讨论】:

  • 文件是否存在?它包含任何东西吗?尝试分而治之的方法:是下载问题,readlines() 方法还是打印问题? minimal reproducible example 将帮助您调试此问题,并帮助我们只关注重要的东西(例如,如果我们知道文件已正确下载,我们可以忽略 curl 命令)。此外,您的代码在 Windows 中不起作用,而最小的示例可能会起作用。

标签: python python-3.x github repository


【解决方案1】:

我试过你的代码,打开文本文件时没有'a+'选项效果很好。
您的代码没有显示任何内容,因为您以“写入”模式打开文件。
您应该将选项设为“r”或“r+”,或者将其保留为默认值。

'r' : 打开阅读(默认)

'a' : 打开写入,如果存在则追加到文件末尾。

'+':打开一个磁盘文件进行更新(读写)

试试:

stats = open('stats.txt')         # select
#stats = open('stats.txt','r')    # one of
#stats = open('stats.txt','r+')   # these
statheadings = stats.readlines()
print(statheadings)

它也会起作用,结果:['404: Not Found\n']

如果你只想检查一个值,你也可以添加索引。

只打印最后一行:

print(satheadings[-1])

结果: 404: Not Found

【讨论】:

  • 非常感谢!我不敢相信我搞砸了。
【解决方案2】:

与其先尝试将文件保存到磁盘,不如直​​接打开它:

import requests
response = requests.get('https://raw.githubusercontent.com/ksu-is/NFLQuarterbackstatIdentifier/master/stats.csv')
print(response.text)

但是,您尝试访问的 URL 给了我 404。这是因为它位于私有存储库中吗?如果是这样,您需要将其存储在可公开访问的位置,以便您的程序可以访问它(或者设置更复杂的身份验证方案)。

【讨论】:

    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多