简体   繁体   English

使用For循环从文件中读取值-Python 3

[英]Using a For loop to read a value from a file - Python 3

I have the following code which doesn't quite work. 我有以下代码无法正常工作。 The function is passed a number (say 1) which is the index number of the film. 向该函数传递一个数字(例如1),该数字是胶片的索引号。 I want the program to display the ROW, for the respective index number (read from the file). 我希望程序显示相应索引号(从文件中读取)的ROW。

def viewfilmfunction(x):
  #Open the file as filmsfile
  with open("films.txt", "r") as filmsfile:
   #call upon the reader that will allow us to work with the file
     filmsfileReader=csv.reader(filmsfile)
     #for each row that is read by the reader
     for row in filmsfileReader:
        #and for each field in that row (this is done automatically)
       for field in row:
           #if the field[x] is equal to the number passed into the sub

        if field==x:
              #print the first two fields in that row which correspond to the number

              print("you have viewed film:",  x, "which is", row)

The text file contents are as follows: 文本文件的内容如下:

0,Genre, Title, Rating, Viewed, Liked
1,Sci-Fi,Out of the Silent Planet, PG, No, No
2,Sci-Fi,Out of the Silent Planet, PG, No, No
3,Sci-Fi,Out of the Silent Planet, PG, No, No
4,Sci-Fi,Out of the Silent Planet, PG, No, No
5,Drama, The English Patient, 15, No, No
6,Drama, Benhur, PG, No, No
7,Drama, The Pursuit of Happiness, 12, No, No
8,Drama, The Thin Red Line, 18, No, No
9,Romance, When Harry met Sally, 12, No, No
10,Romance, You've got mail, 12, No, No
11,Romance, Last Tango in Paris, 18, No, No
12,Romance, Casablanca, 12, No,No

Currently the output is: 0 G 当前输出为:0 G

1 SO 1个

2 SO 2 SO

3 SO 3 SO

4 SO 4 SO

5 D 5天

6 D 6天

7 D 7天

8 D 8天

9 R 9 R

1 R 1个

1 R 1个

1 R 1个

N ñ

I would like the output to be as below, outputting only the second and third fields in the respective row (the genre and title): 我希望输出如下,仅输出相应行中的第二个和第三个字段(类型和标题):

"You have viewed film: 1 which is SCI-FI, Out of the Silent Planet"

如果我了解您必须检查if row[0] == x

Start using pandas 开始使用熊猫

import pandas as pd
df = pd.read_csv("films.txt")
df.loc[n,]

Gives the desired result. 提供所需的结果。 This is all the code not an extract. 这是所有代码,而不是摘录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM