Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将文件中的信息转换为python?_Python - Fatal编程技术网

如何将文件中的信息转换为python?

如何将文件中的信息转换为python?,python,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" 然后在我的代码中使用此文件中的一些

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

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()
我需要的是读取filein中的第一行,然后获取V4[1],V5[1]值,并在代码中使用它们,然后在输出中使用它们

对第二行(V4[2],V5[2])和所有行(做一个循环)执行相同的操作

我是Python新手,如果这个问题看起来很简单,那么很抱歉

我的输出(已保存)为:


仅设置正确的分隔符:

with open('datasets.txt', 'r', encoding = 'UTF-16') as ids:
    reader = csv.reader(ids, delimiter = '\n')
    ids = [x for x in reader]
print(ids[0]) #This is First line
for x in ids:
    print(x[4],x[5]) #These are V5 and V6

以下是一个简单的解决方案:

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()

这里您想要的输出是什么?第一次迭代:确定您需要查找的索引。下一次迭代:访问先前确定的索引,并计算它们。这个解释对你来说够简单吗?我的输出是文件。我想区分输出文件,所以我在文件名中输入了我使用的内容:
filename\u V4\u V5.txt
。您只需要从文件中读取特定值并将它们分配给变量。然后在需要引用这些值的地方使用这些变量。当您更新问题时,我现在明白了。@TEM或抱歉,我忘了将它们转换为整数。我刚刚更新了我的答案。
with open('datasets.txt', 'r', encoding = 'UTF-16') as ids:
    reader = csv.reader(ids, delimiter = '\n')
    ids = [x for x in reader]
print(ids[0]) #This is First line
for x in ids:
    print(x[4],x[5]) #These are V5 and V6
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()