如何从文件中获取信息到python?

时间:2018-01-08 11:13:25

标签: python

我有一个文件,我可以这样读:

filein= open('/path/datasets.txt', 'r')
print filein.read()
"V1" "V2" "V3" "V4" "V5" "V6" "V7" "V8" "V9"
"1" "ABCD" "ABCD" "Adam" "29" "591" "25" "54" "25" "NH"
"2" "ABCD" "ABCD" "Alex" "481" "26" "75" "54" "25" "NH"

然后在我的代码中使用此文件中的某些格式:

 Import   …….
 res = data.read(29,591) # res = data.read(V4 [1],V5 [1])
 fileout = open('filename_29_591.txt', 'w') # 'filename_V4 [1]_V5 [1].txt
 fileout.write(res.to_string())
 fileout.close()

我需要的是在我的文件中读取第一行然后取V4 [1],V5 [1]值并在代码中使用它们然后在输出中。

对第二行(V4 [2],V5 [2])和所有行(进行循环)执行相同操作。

 res = data.read(481,26) # res = data.read(V4 [2], V5 [2])
 fileout = open('filename_481_26.txt', 'w') # 'filename_V4 [2]_V5 [2].txt
 fileout.write(res.to_string())
 fileout.close()

我对Python很陌生,如果问题看起来很简单,那就很抱歉。

我的输出(保存)是:

           filename_29_591.txt
           filename_481_26.txt

2 个答案:

答案 0 :(得分:1)

仅设置正确的分隔符:

Jan 08, 2018 7:16:46 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Redeploying!
Stopping vert.x application '58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy'
Application '58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy' terminated with 
status 0
'.' is not recognized as an internal or external command,
operable program or batch file.
Jan 08, 2018 7:16:47 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: User command terminated with status 1
Starting vert.x application...
58d1ec56-6d4c-4209-9fba-71cd6f54101c-redeploy
Jan 08, 2018 7:16:47 PM io.vertx.core.impl.launcher.commands.Watcher
INFO: Redeployment done in 966 ms.
Jan 08, 2018 7:16:48 PM 
io.vertx.core.impl.launcher.commands.VertxIsolatedDeployer
INFO: Succeeded in deploying verticle

答案 1 :(得分:1)

这是一个简单的解决方案:

filein = open('/path/datasets.txt', 'r')
lines = filein.readlines()
filein.close()

for line in lines[1:]:
    fields = line.split(' ')
    V4 = int(fields[4].strip('"'))
    V5 = int(fields[5].strip('"'))
    # do something with V4 and V5
    res = data.read(V4, V5)
    fileout = open('filename_{}_{}.txt'.format(V4, V5), 'w')
    fileout.write(res.to_string())
    fileout.close()