Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

Files and loops

Opening a file with different modes (Read, write etc.)

open("story.txt", "r")

“r”- reading mode

Reading a file-

f = open("test.txt", "r")

g = f.read()

print(g)

Splitting data-

Mumbai,421\nDelhi,123

\n changes to next line

\t space

Data = “A,B,C”

F = data.split(“,”)

Print(f) – [ ‘A’, ‘B’, ‘C’]

Or (“\n”)

import os

print(os.getcwd())

path = os.chdir(r"\Users\pushpak\desktop\datasets\dataquest\file_loops")

Loops-

For loop

for city in cities:

Print(city)
Here, city is a temporary variable.

Loops assigns the index and apply logic

List of lists

three_rows = ["Albuquerque,749", "Anaheim,371",


"Anchorage,828"]
final_list = []

for row in three_rows:


split_list = row.split(',')
final_list.append(split_list)
print(final_list)

out- [['Albuquerque', '749'], ['Anaheim', '371'], ['Anchorage', '828']]

Accessing the list

# Returns the first list: ['Albuquerque', '749'].


first_list = final_data[0]

# Returns the first list's first element: 'Albuquerque'.


first_list_first_value = first_list[0]

# Returns the first list's first element, 'Albuquerque'.


first_list_first_value = final_data[0][0]
# Returns the second list's first element, 'Anaheim'.
second_list_first_value = final_data[1][0]
# Returns the third list's first element, 'Anchorage'.
third_list_first_value = final_data[2][0]

Looping through a list of lists

city_names = []

for city in final_list:

city_name = city [0] #index

city_names.append(city_name)

print(city_names)

You might also like