# File Handling Assignments

1. Write a Python program to read a file line by line and print its contents.

```python
file = open("sample.txt", "r")
for line in file:
    print(line)
file.close()
```

2. Write a Python program to count the number of lines in a file.

```python
file = open("sample.txt", "r")
count = 0
for line in file:
    count += 1
print("Number of lines in file:", count)
file.close()
```

3. Write a Python program to append text to an existing file.

```python
file = open("sample.txt", "a")
file.write("This text will be appended to the end of the file.\n")
file.close()
```

4. Write a Python program to read the last n lines of a file.

```python
def read_last_n_lines(file_name, n):
    with open(file_name, "r") as file:
        lines = file.readlines()
        return "".join(lines[-n:])

print(read_last_n_lines("sample.txt", 3))
```

5. Write a Python program to remove the newline character from the end of each line in a file.

```python
with open("sample.txt", "r") as file:
    lines = file.readlines()

with open("sample.txt", "w") as file:
    for line in lines:
        file.write(line.strip() + "\n")
```

6. Write a Python program to copy the contents of one file into another.

```python
with open("file1.txt", "r") as file1:
    with open("file2.txt", "w") as file2:
        file2.write(file1.read())
```

7. Write a Python program to find the longest word in a file.

```python
with open("sample.txt", "r") as file:
    words = file.read().split()
    longest_word = max(words, key=len)
print("Longest word in file:", longest_word)
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://training.gitbook.io/python-assignments/file-handling-assignments.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
