|
| 1 | +# -w is used to write inside a file |
| 2 | +# if file doesnt exist, it creates one |
| 3 | +# if file exists, it overwrites the file |
| 4 | +with open("example.txt", "w") as file: |
| 5 | + file.write("this is file handling") |
| 6 | + file.write("\n-w mode is used to write inside a file") |
| 7 | +print("file written successfully") |
| 8 | + |
| 9 | +# -r is used to read the contents of a file |
| 10 | +# if file doesnt exist, it throws an err |
| 11 | +with open("example.txt", "r") as file: |
| 12 | + content = file.read() |
| 13 | +print(content) |
| 14 | + |
| 15 | +# 'a' mode: Keeps the existing content and adds new data |
| 16 | +with open("example.txt", "a") as file: |
| 17 | + file.write("\n-a is used for appending in the same file") |
| 18 | +print("appended") |
| 19 | + |
| 20 | +# to read file line by line |
| 21 | +with open("example.txt", "r") as file: |
| 22 | + for line in file: |
| 23 | + print(line.strip()) # strip() remove the newline character |
| 24 | + |
| 25 | +# Write a Python script to create a file named "data.txt" and write 5 lines of text. |
| 26 | +with open("data.txt", "w") as file: |
| 27 | + file.write("this is a practice question\nline 1\nline 2\nline 3\nline 4") |
| 28 | +print("data.txt created and written") |
| 29 | +# optimised code: |
| 30 | +# with open("data.txt", "w") as file: |
| 31 | +# lines = ["this is a practice question\n", |
| 32 | +# "line 1\n", |
| 33 | +# "line 2\n," |
| 34 | +# "line 3\n," |
| 35 | +# "line 4\n"] |
| 36 | +# file.writelines(lines) |
| 37 | + |
| 38 | + |
| 39 | +# Read the file and print each line one by one. |
| 40 | + |
| 41 | +with open("data.txt", "r") as file: |
| 42 | + content = file.readlines() |
| 43 | + total_words = 0 |
| 44 | + total_char = 0 |
| 45 | + for line in content: |
| 46 | + print(line.strip()) |
| 47 | + total_words += len(line.split()) |
| 48 | + total_char += len(line) |
| 49 | +# Count the number of lines in "data.txt" and print: |
| 50 | +# "Total number of lines in data.txt: X" |
| 51 | + print(f"Total number of lines in data.txt: {len(content)}") |
| 52 | +# Modify your script to count the total number of words in "data.txt" and print: |
| 53 | +# "Total number of words in data.txt: X" |
| 54 | + print(f"Total number of words in data.txt: {total_words}") |
| 55 | +# Count the total number of characters in "data.txt" and print: |
| 56 | +# "Total number of characters in data.txt: X" |
| 57 | + print(f"Total number of characters in data.txt: {total_char}") |
0 commit comments