f = open('/my_path/my_file.txt', 'r')
with open('/my_path/my_file.txt', 'r') as f: file_data = f.read() camelot_lines = [] with open("camelot.txt") as f: for line in f: camelot_lines.append(line.strip()) print(camelot_lines)
def create_cast_list(filename): cast_list = [] with open(filename) as f: for line in f: line_data = line.split(',') cast_list.append(line_data[0]) return cast_list
The Python Standard Library is organised into parts called modules. Many modules are simply Python files, like the Python scripts you’ve already used and written. In order to be able to use the code contained in a module we must import it, either in the interactive interpreter or in a Python script of our own.
The syntax for importing a module is simply import package_name.
>>> import math >>> print(math.factorial(3)) 6
from module_name import object_name
e.g.
from collections import defaultdict
>>> import multiprocessing as mp
>>> mp.cpu_count()
4
import an individual item from a module and give it a different name
from module_name import object_name as different_name
from csv import reader as csvreader
Python Standard Library
csv, collections, random, string, re, math, os, os.path, sys, json
word_file = “words.txt”
word_list = []
with open(word_file, ‘r’) as words:
for line in words:
word = line.strip().lower()
if 3 < len(word) < 8
word_list.append(word)
[/python]
[python]
def generate_password():
return random.choice(word_list) + random.choice(word_list) + random.choice(word_list)
def generate_password():
return str().join(random.sample(word_list,3))
[/python]