python - 带有枚举的基本 python 文件 io 变量

标签 python file-io enumerate

Python 新手,正在尝试学习文件 I/O 的诀窍。

我正在使用这种格式从大型(200 万行)文件中提取行:

56fr4
4543d
4343d
5irh3

这是我用来返回代码的函数:

def getCode(i):
    with open("test.txt") as f:
        for index, line in enumerate(f):
            if index == i:
                code = # what does it equal?
                break
    return code

一旦索引到达正确的位置 (i),我应该使用什么语法来设置代码变量?

最佳答案

code = line.strip()

将代码分配给等于 i 的行号,同时删除尾随的新行。

你还需要稍微更新一下你的代码

 def getCode(i):
    with open('temp.txt', 'r') as f:
             for index, line in enumerate(f):
                     if index == i:
                             code = line.strip()
                             return code

为什么需要 .strip()

>>> def getCode(i):
...     with open('temp.txt') as f:
...             for index, line in enumerate(f):
...                     if index == i:
...                             code = line
...                             return code
 ... 
>>> getCode(2)
"                  'LINGUISTIC AFFILIATION',\n"

是的,“'LINGUISTIC AFFILIATION',”在我当前的 temp.txt 中

关于python - 带有枚举的基本 python 文件 io 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6473283/

相关文章:

python - 为什么一个CNN的loss会长时间下降然后突然上升?

Python File IO - 构建字典并查找最大值

python - 如何迭代 azure.core.paging.ItemPaged?

windows - 为什么枚举 session 在 Windows 7 上有额外的好处?

python - 在 CSV python 中添加列并枚举它

python - 在同一 Tensorflow session 中从 Saver 加载两个模型

Python str() - 指定要添加/使用哪种引号?

python - 如何测试 Connexion/Flask 应用程序?

java - 如何在写入文件的同时将文件分成 block ?

excel - MATLAB 中 xlsread 速度慢