Язык программирования Python используется не только для кодирования, но и для обработки файлов. Файлы, которые обычно обрабатываются, имеют расширение .txt.
Для начала вы можете начать с открытия файла. Disini saya akan menyiapkan file.txt bernama myfile yang disimpan di d: di dalamnya akan saya tulis sebuah kata berupa «тестирование».
Пример
file = open("d:/myfile.txt") read_file = file.read() print(read_file)
Выход:
- Если в d: нет файла с именем «myfile.txt», будет отображаться сообщение об ошибке
-------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-3-9660184a7868> in <module> ----> 1 file = open("d:/myfile.txt") 2 read_file = file.read() 3 print(read_file) FileNotFoundError: [Errno 2] No such file or directory: 'd:/myfile.txt'
- Но если в d: есть файл с именем «myfile.txt», то результат
Testing
Приведенный выше пример программы на самом деле все еще не очень хорош, потому что, если Python только открывает файл(), это может привести к повреждению файла, который он вызывает. Все, что начинается с open(), должно заканчиваться на close().
Пример
# Open file with path file file = open("d:/myfile.txt") # To read the text in the file read_file = file.read() print(read_file) # For close the file file.close()
Выход:
Testing
Однако, если вы боитесь, что забудете закрыть файл, вы можете использовать другой метод, например with().
with open("d:/myfile.txt", "r") as file: read = file.read() print(read)
Выход:
Testing
При использовании with нам больше не нужно использовать метод close(), потому что он автоматически выполняется python.
Python может манипулировать им с помощью различных режимов аргументов. Каждый режим имеет различные характеристики и использование. Вот режимы аргументов в Python:
Стол
| r r+ w w+ a a+
------------------|--------------------------
read | + + + +
write | + + + + +
write after seek | + + +
create | + + + +
truncate | + +
position at start | + + + +
position at end | + +
1. “r”
Читать — Только для чтения и его положение в начале.
Пример
# Open file with path file file = open("d:/data.txt", "r") # To read the text in the file read_file = file.read() print(read_file) # For close the file file.close()
Выход:
10 0 a 20 30 40 b 80
2. r+
Read + — Может использоваться для чтения и записи. Позиция в начале.
Пример
# Open file with path file file = open("d:/file1.txt", "r+") # To read the text in the file read_file = file.read() print(read_file) # For close the file file.close()
Выход:
100 102 99 89 192 938 107 241
3. w
Запись — полезно для записи файла, если он не существует, и содержимого файла, если файл уже существует. Позиция в начале.
Пример
file = open("d:/MyFileAgain.txt", "w") file.write("Hi, my name is Hanizar") file.close()
Выход:
4. w+
Write+ — полезно для чтения и записи файлов. Если файл не существует, он будет создан автоматически, но если файл уже существует, содержимое файла будет усечено. Позиция в начале.
Пример
# Open or create file with path file file = open("d:/myfile.txt", "w+") # Write text into file file.write("I Love Python") # For close the file file.close()
Выход:
5. a
Append — полезно для записи. Если файл не существует, он будет создан автоматически. Позиция в конце.
Пример
# Open or create file with path file file = open('d:/myfile.txt', "a") # Write text into file file.write("You Love Python?") # Close the file file.close()
Выход:
Because the mode argument a cannot truncate the contents of the text in the file, nor is it positioned at the end. Then the output obtained, as in the picture above.
6. a+
Append+ — полезно для чтения и записи. Если файл не существует, он будет создан автоматически. Позиция в конце.
Пример
file = open('d:/myfile.txt', "a+") # Write text into file file.write("Yes, I love it") # Read and Print text from file read = file.read() print(read) # For close the file file.close()
Выход:
1. В запущенных программах
# EMPTY
2. В файле
There is a difference when it is run with mode a and a+, in the result file, it turns out that the text previously entered by mode a, has been replaced/cut by text with mode a+. Both are the same starting from the final position. Even in the program, even though this a+ mode can read files, why does it not appear when ordered to print/read text in the file? Because a+ is at the end, therefore, it will print from where the pointer is, for that, you can use seek(), to set the pointer position.
Пример печати текста в файле
# Open file file = open('d:/myfile.txt', "a+") # Write text into file file.write("Yes, I love it") # Sets the pointer, starting at 0 file.seek(0) # Read and Print text from file read = file.read() print(read) # For close the file file.close()
Выход:
- В программе
I Love PythonYes, I love it
- В файле
Видеть! Положение указателя теперь в начале.