Python File Handle Part 1
Автор: ಜ್ಞಾನದ ಹರಿವು_Knowledgeflow@MallammaVReddy
Загружено: 2025-11-19
Просмотров: 2
Описание:
Python provides robust capabilities for file handling, allowing programs to interact with files on the operating system. This includes operations such as creating, opening, reading, writing, appending, and managing files.
1. Opening Files:
The open() function is the primary method for interacting with files. It takes the file name (or path) and the mode as arguments.
Python
file = open("filename.txt", "mode")
Common Modes:
'r' (read): Opens for reading (default).
'w' (write): Opens for writing, overwriting existing content or creating a new file.
'a' (append): Opens for appending, adding content to the end of an existing file or creating a new file.
'x' (create): Creates a new file; raises an error if the file already exists.
't' (text): Opens in text mode (default).
'b' (binary): Opens in binary mode (e.g., for images or executables).
2. Reading from Files:
read(): Reads the entire content of the file.
readline(): Reads a single line from the file.
readlines(): Reads all lines into a list of strings.
Iterating: You can loop directly over the file object to read line by line.
Python
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Remove newline characters
3. Writing to Files:
write(string): Writes a string to the file.
writelines(list_of_strings): Writes a list of strings to the file.
Python
with open("output.txt", "w") as file:
file.write("This is the first line.\n")
file.write("This is the second line.")
with open("data.txt", "a") as file:
file.write("\nNew data appended.")
4. Closing Files:
It is crucial to close files after use to release system resources. The close() method is used for this.
Python
file = open("my_file.txt", "r")
... operations ...
file.close()
with statement (Recommended):
The with open(...) as ...: statement ensures that the file is automatically closed, even if errors occur.
Python
with open("safe_file.txt", "w") as file:
file.write("This file will be closed automatically.")
5. File Management (using os module):
os.rename(old_name, new_name): Renames a file.
os.remove(filename): Deletes a file.
os.mkdir(directory_name): Creates a new directory.
os.listdir(path): Lists contents of a directory.
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: