File Handling

Understanding how to read from and write to files, and handling file paths.


1

How do you read the contents of a file in Python?

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

2

How do you write text to a file in Python?

with open('example.txt', 'w') as file:
    file.write('Hello, World!')

3

How do you append text to an existing file?

with open('example.txt', 'a') as file:
    file.write('\nAppended text.')

4

How can you read a file line by line?


5

How do you read a specific number of bytes from a file?


6

How can you check if a file exists before reading it?


7

How do you handle exceptions when working with files?


8

How do you get the current working directory?


9

How can you change the current working directory?


10

How do you write a list of strings to a file, each on a new line?


11

How can you read a file into a list of lines?


12

How do you delete a file?


13

How do you rename a file?


14

How do you copy a file to a new location?


15

How can you move a file to a new location?


16

How do you create a new directory?


17

How can you list all files in a directory?


18

How do you read binary data from a file?


19

How do you write binary data to a file?


20

How can you use os.path.join to handle file paths?


21

How do you get the size of a file?


22

How can you use pathlib to handle file paths?


23

How do you check if a path is a file or directory using pathlib?


24

How can you read a CSV file into a list of dictionaries?


25

How do you write a list of dictionaries to a CSV file?


Last updated