Create a List that contain each Line of a File

前端 未结 8 1509
无人及你
无人及你 2020-12-23 16:52

I\'m trying to open a file and create a list with each line read from the file.

   i=0
   List=[\"\"]
   for Line in inFile:
      List[i]=Line.split(\",\")
         


        
8条回答
  •  伪装坚强ぢ
    2020-12-23 17:09

    A file is almost a list of lines. You can trivially use it in a for loop.

    myFile= open( "SomeFile.txt", "r" )
    for x in myFile:
        print x
    myFile.close()
    

    Or, if you want an actual list of lines, simply create a list from the file.

    myFile= open( "SomeFile.txt", "r" )
    myLines = list( myFile )
    myFile.close()
    print len(myLines), myLines
    

    You can't do someList[i] to put a new item at the end of a list. You must do someList.append(i).

    Also, never start a simple variable name with an uppercase letter. List confuses folks who know Python.

    Also, never use a built-in name as a variable. list is an existing data type, and using it as a variable confuses folks who know Python.

提交回复
热议问题