9 Reading and Writing Files Flashcards
How can you:
1. Create paths that work for your operating system
- Does it matter if you use / or \ in your code?
- Using the Path module:
»>from pathlib import Path
»>path(‘spam’, ‘eggs’,’what’)
WindowsPath(‘spam/bacon/eggs’) - It does, as Windows uses ! But using pathlib, which is newer than os.path, allows you to always use / in your code.
How can you:
1. Create a path-text string
- What is different in the text string and why is it necessary?
- Using str(path(message)):
»>str(path(‘spam’, ‘eggs’,’what’)
‘spam\bacon\eggs’ - It creates 2 backslashes -because each backslash needs to be escaped by another backslash character
- What can Path & backslashes do?
- What does they evaluate to?:
> > > Path(‘spam’) / ‘bacon’ / ‘eggs’
Path(‘spam’) / Path(‘bacon/eggs’)
Path(‘spam’) / Path(‘bacon’, ‘eggs’)
- They work like ‘+’ in the string concatenation
- They evaluate to:
WindowsPath(‘spam/bacon/eggs’)
How can you find out your current working directory and change it?
> > > from pathlib import Path
import os
Path.cwd()
os.chdir(‘C://targetFolder’)
Create a folder named ‘waffles’,
inside a folder named ‘walnut’,
inside a folder named ‘delicious’,
in the C:/ folder
How can you create a single folder within ‘walnut’?
os.makedirs(‘C:\delicious\walnut\waffles’)
Path(r’C:\delicious\walnut\waffles\spam’).makedir()
-> No ‘s’ in the end!
- What do ‘.’ and ‘..’ indicate?
- How can you return a string of the absolute path?
- How can you return a relative path from A to B? What happens if B is not given?
- ’.’ current folder
‘..’ parent folder - os.path.abspath(path)
»>os.path.abspath(‘.’) - os.path.relpath(A, B)
If B is not given, the current folder is used. So (A, ‘.’) == (A)
C:\Users\Al\spam.txt
- Explain:
Name, Parent, Drive, Stem, Suffix and Anchor - How can you find each of them out?
C:\Users\Al\spam.txt
1. Drive: Only on Win 'C:' Anchor: root folder 'C:\' Parent: folder that contains file 'Users\Al\' Stem: spam Suffix: .txt Name: spam.txt
- Pass the path to a variable:
p = Path(‘C:\Users\Al\spam.txt’)
Than: variable.*
* –> anchor, parent…etc., e.g.
»>p.anchor
‘C:\’
How can you find out the size that all files and folders within a certain folder have?
Root folder:
C:\Windows\System32
size = 0 for file in os.listdir('C:\\Windows\\System32'): size = size + os.path.getsize (os.path.join ('C:\\Windows\\System32', file)
The Join-Method combines folder and filenames - this part might be redundant.
- How can you check whether a file or a folder path exist?
2. How would you check if a DVD is in your Computer?
1. Assign path to variable p >>>p.exists() >>>p.is_file() returns True or False
- dDrive = Path(‘D:')
dDrive.exists()
»>False
Name 2x ways to open an existing file ‘hello.txt’ in your home folder.
- open(Path.home() / ‘hello.txt’)
2. open(‘C:\Users\Yassin\hello.txt’)
What is a File object? What methods can you use?
It is a value type, just like a list or a dictionary.
filename.*()
* –> open()
write()
read()
readlines() -> list value
How can you write to a text file, append additional information and than read its contents?
- Pass ‘w’ or ‘a’ as the second argument to open(). Pass it to a variable
»>spam = open(filename, ‘w’) - Pass write() to the variable
»>spam.write(‘meassage’) - Close it
»>spam.close() - Re-Open in append mode»_space;>spam = open(filename, ‘a’)
- > > > spam.write(‘MESSAGE’)
- > > > spam.close()
- Re-Open in read mode
»>spam = open(filename, ‘r’) - Pass read() to a NEW variable
»>content = spam.read()
9.»>spam.close() - Print text
»>print(content)
message
MESSAGE
What is the benefit of the shelve module? 2x
What does it save?
What values does it contain?
txt.files are good for plain text, but to save data, e.g. from Python programmes, shelve is better.
Its open function works for both reading and writing
It creates 3 binary files.
It works like a dictionary, with keys and values.
How can you store a list in a shelve File ‘mydata’ and add it to the key ‘cats’?
>>>import shelve >>>catsList = ['Soo', 'Poo', 'Joke'] >>>shelfFile = shelve.open('mydata') >>>shelfFile[cats]='catsList' >>>shelfFile.close()
> > > shelfFile = shelve.open(‘mydata’)
shelfFile[cats]
[‘Soo’, ‘Poo’, ‘Joke’]