- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to work with a text file in Python?
A text file is any file containing only readable characters. The opposite of text files,"binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs orGIFs, audio files like MP3s or binary document formats like Word or PDF. The main difference between a text file and a binary file is that binary files need special programs (or knowledge of the special format) to make sense. Text files can be edited by any program that edits plain text, and are easy to process in programming languages like Python.
f = open('my_file.txt', 'r+') my_file_data = f.read() f.close()
The above code opens 'my_file.txt' in read mode then stores the data it reads from my_file.txt in my_file_data and closes the file. Files are opened in text mode by default in Python and can be directly read/written. The read function reads the whole file at once. You can use the following to read the file line by line:
f = open('my_file.txt', 'r+') for line in f.readlines(): print line f.close()
You can also write to text files. For example, if you want to overwrite my_file.txt, you'd open it in write mode and write to it:
f =open("my_file.txt", "w") f.write("My File!") f.close()
You can also append to existing files using the append mode. Opening a file in append mode sets the file pointer to the end of file. Any consequent write statements that are executed add data to the end of the file.
- How to read a text file in Selenium with python?
- How to write a text file in Selenium with python?
- How to read a text file in Python?
- How to read a text file with C++?
- How to read text file into a list or array with Python?
- How to create a Python dictionary from text file?
- How to append text to a text file in C++?
- How to upload a file in Selenium with no text box?
- How to search and replace text in a file using Python?
- How to write a single line in text file using Python?
- How to find and replace within a text file using Python?
- How to work with cookies in Selenium with python?
- How to write multiple lines in text file using Python?
- How to open a plain text file in C#?
- How to open a plain text file in Java?