问题标签 [linecache]
For questions regarding programming in ECMAScript (JavaScript/JS) and its various dialects/implementations (excluding ActionScript). Note JavaScript is NOT the same as Java! Please include all relevant tags on your question; e.g., [node.js], [jquery], [json], [reactjs], [angular], [ember.js], [vue.js], [typescript], [svelte], etc.
python - 使用 linecache 时跳过文件的第一行
我使用 linecache 在 Pytorch 中创建了一个惰性数据加载器。它从一个 tsv 文件中提取,我也使用该文件来使用 Pytorch 的 build_vocab 构建词汇表,因此我需要为每一列设置一个标题行。
对于我使用 getitem 的数据集:
但是,由于 linecache 不会将整个文件加载到内存中,因此没有明显的方法可以跳过 tsv 文件的第一行/标题。我尝试了“if index == 0: pass”,但这显然返回了 None ,这引发了一个不同的错误。
我目前的解决方案是只有两个 tsv,一个有标题,一个没有。
python - Python - getline() 方法不打印“换行符”
我对 python 比较陌生,我正在制作一个小游戏,其中涉及从 .txt 文件中导入每一行文本,以便可以将其打印给用户。为此,我使用 linecache.getline() 来获取我想要的文件的特定行,而不是将整个文件存储为列表。但是,如果我使用 "\n" 创建一个新行,则 linecache.getline() 会自动插入另一个反斜杠以“取消”它。
例如,如果在我写的文本文件中
\nHello
,linecache.getline() 会将其存储在变量 as
\\nHello
which prints as 中
\nHello
。
有没有办法阻止这种情况?如果需要,我可以发布我的特定代码。
任何有关文件操作的帮助将不胜感激,因为我对它很陌生,并感谢您查看我的问题。
python - 使用 linecache.getline 读取 GB2312 编码文件
我需要读取具有给定行号的 GB2312 编码文件中的指定行。很多人提到linecache.getline(file_path,line_no)
的是正确答案。但是
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 72: invalid continuation byte
当我尝试读取 GB2312 文件时它出现了,同时使用 utf-8 文件。
但是,在 Python 文档中,linecache.getline()
我没有找到任何指定编码方法的参数。
所以我想知道是否linecache.getline()
能够读取非 utf-8 文件?如果是,如何?
这是一个最小的可重现示例。
将以下带有中文字符的文本存储为test.txt。然后使用 vs-code 或 notpad++ 将其转换为 GB2312 编码。