How do you open specific text files on python? - python

I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?

presuming that you want the line m and the name file is file.txt
with open('file.txt') as f:
line = f.read().splitlines()[m]
print(line)
line is the line that you want.

If the lines are selected by line numbers which follow a consistent pattern, use
itertools.islice.
E.g. To select every second line from line 3 up to but not including line 10:
import itertools
with open('my_file.txt') as f:
for line in itertools.islice(f, 3, 10, 2):
print(line)

First lets see how to open a file to write:
f = open(‘filename.txt’, ‘w’)
Now we have opened a file named filename, in write mode. Write mode is indicated using ‘w’. If a file of that particular name is not present then a new file would be created.
It has created an object of that particular file and we can do all our operations on that particular object. Now we have created an object for writing. The command to write is:
text = “Hello Python”
f.write(text) ## or f.write(“Hello Python”)
After doing all our required operations, we need to close the file. The command to close the file is as follows:
f.close()
This will save the file and close it. Now lets see how to read a file.
f = open(‘filename.txt’, ‘r’)
Same like write, but only the mode is changed to ‘r’. Now we have opened a file named filename, in read mode. Read mode is indicated using ‘r’. If a file of that particular name is not present then an error will be raised
Traceback (most recent call last):
File "", line 1, in
IOError: [Errno 2] No such file or directory: 'filename.txt'
If the file is present, then it would create an object of that particular file and we can do all our operations on that particular object. Now we have created an object for reading. The command to read is:
text = f.read()
print text
All the contents of the file object is now read and stored in the variable text. Text holds the entire contents of the file.
After doing all our required operations, we need to close the file. The command to close the file is as follows:
f.close()
In the above examples we have opened the file separately and close it separately, there is a better way to do it using with function. The modified code will be
with open(‘filename.txt’, ‘r’) as f:
text = f.read()
print text
When it comes out of the with block it will automatically close the file.

Related

How to re sub a pattern in a file [duplicate]

I have this code:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
But when I try it, I get an error message like:
File "...", line 18, in <module>
for line in file:
UnsupportedOperation: not readable
Why? How do I fix it?
You are opening the file as "w", which stands for writable.
Using "w" you won't be able to read the file. Use the following instead:
file = open("File.txt", "r")
Additionally, here are the other options:
"r" Opens a file for reading only.
"r+" Opens a file for both reading and writing.
"rb" Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w" Opens a file for writing only.
"a" Open for writing. The file is created if it does not exist.
"a+" Open for reading and writing. The file is created if it does not exist.
Use a+ to open a file for reading, writing and create it if it doesn't exist.
a+ Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing. -Python file modes
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")
Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.
more modes:
r. Opens a file for reading only.
rb. Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w. Opens a file for writing only.
you can find more modes in here
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
Sreetam Das's table is nice but needs a bit of an update according to w3schools and my own testing. Unsure if this due to the move to python 3.
"a" - Append - will append to the end of the file and will create a file if the specified file does not exist.
"w" - Write - will overwrite any existing content and will create a file if the specified file does not exist.
"x" - Create - will create a file, returns an error if the file exist.
I would have replied directly but I do not have the rep.
https://www.w3schools.com/python/python_file_write.asp

Python error message io.UnsupportedOperation: not readable

I have this code:
line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")
file = open("File.txt","w")
for i in range(3):
file.write(line1[i])
file.write("\n")
for line in file:
print(line)
file.close()
But when I try it, I get an error message like:
File "...", line 18, in <module>
for line in file:
UnsupportedOperation: not readable
Why? How do I fix it?
You are opening the file as "w", which stands for writable.
Using "w" you won't be able to read the file. Use the following instead:
file = open("File.txt", "r")
Additionally, here are the other options:
"r" Opens a file for reading only.
"r+" Opens a file for both reading and writing.
"rb" Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w" Opens a file for writing only.
"a" Open for writing. The file is created if it does not exist.
"a+" Open for reading and writing. The file is created if it does not exist.
Use a+ to open a file for reading, writing and create it if it doesn't exist.
a+ Opens a file for both appending and reading. The file pointer is at
the end of the file if the file exists. The file opens in the append
mode. If the file does not exist, it creates a new file for reading
and writing. -Python file modes
with open('"File.txt', 'a+') as file:
print(file.readlines())
file.write("test")
Note: opening file in a with block makes sure that the file is properly closed at the block's end, even if an exception is raised on the way. It's equivalent to try-finally, but much shorter.
There are few modes to open file (read, write etc..)
If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.
more modes:
r. Opens a file for reading only.
rb. Opens a file for reading only in binary format.
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in binary format.
w. Opens a file for writing only.
you can find more modes in here
This will let you read, write and create the file if it don't exist:
f = open('filename.txt','a+')
f = open('filename.txt','r+')
Often used commands:
f.readline() #Read next line
f.seek(0) #Jump to beginning
f.read(0) #Read all file
f.write('test text') #Write 'test text' to file
f.close() #Close file
Sreetam Das's table is nice but needs a bit of an update according to w3schools and my own testing. Unsure if this due to the move to python 3.
"a" - Append - will append to the end of the file and will create a file if the specified file does not exist.
"w" - Write - will overwrite any existing content and will create a file if the specified file does not exist.
"x" - Create - will create a file, returns an error if the file exist.
I would have replied directly but I do not have the rep.
https://www.w3schools.com/python/python_file_write.asp

Python File I/O:How to know if text exist on a line and go to the next line

In python file io I get just frustrated because, when I try to write to the next line it just doesnt seem to work.
Ive tried "\n" but It just erases the existing text in the file
fo = open("acckeys.txt","w+")
fo.write(psw+"_"+usr+"\n")
So how would I check if text already exists in a line and write to the next line without erasing the existing text?
If you open the file with the append flag, it will write to the next free line.
fo = open("file.txt", "a")
Note you can also open with "a+" to allow reading as well.
"a+":
Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file.
With respect to the statement
fo = open("acckeys.txt")
It will open the acckeys.txt file in a read mode, I assume this file already exists, Otherwise It will throw IOError with the error message "No such file or directory: 'acckeys.txt'"
And This line will write to the file from the pointer it is currently pointing to. You can find out the current pointer using seek() of file handle, (fo in this case). Usually current offset pointer is the starting of file.
fo.write(psw+"_"+usr+"\n")
Now your question
So how would I check if text already exists in a line and write to the next line without erasing the existing text?
In order to check if the text exist in the file, you can read the file using
fileContent = fo.read()
And then check for the length of fileContent.
If you open a file in an append mode like this
fo = open("acckeys.txt" ,"a")
then irrespective of the file content or non-existent of the file itself. It will create a file incase of non-existent or set the offset pointer to the last line.

Open/write deleting txt file contents?

I am bassicly trying to read a number from a file, convert it to an int, add one to it, then rewrite the new number back to the file. However every time I run this code when i open the .txt file it is blank. Any help would be appreciated thanks! I am a python newb.
f=open('commentcount.txt','r')
counts = f.readline()
f.close
counts1 = int(counts)
counts1 = counts1 + 1
print(counts1)
f2 = open('commentcount.txt','w') <---(the file overwriting seems to happen here?)
f2.write(str(counts1))
Having empty files
This issue is caused by you failing to close the file descriptor. You have f.close but it should be f.close() (a function call). And you also need an f2.close() in the end.
Without the close it takes a while until the contents of the buffer arrive in the file. And it is a good practice to close file descriptors as soon as they are not used.
As a side note, you can use the following syntactic sugar to ensure that the file descriptor is closed as soon as possible:
with open(file, mode) as f:
do_something_with(f)
Now, regarding the overwriting part:
Writing to file without overwriting the previous content.
Short answer: You don't open the file in the proper mode. Use the append mode ("a").
Long answer:
It is the intended behavior. Read the following:
>>> help(open)
Help on built-in function open in module __builtin__:
open(...)
open(name[, mode[, buffering]]) -> file object
Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.
>>> print file.__doc__
file(name[, mode[, buffering]]) -> file object
Open a file. The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending. The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing. Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size. The preferred way
to open a file is with the builtin open() function.
Add a 'U' to mode to open the file for input with universal newline
support. Any line ending in the input file will be seen as a '\n'
in Python. Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.
So, reading the manuals shows that if you want the content to be kept you should open in append mode:
open(file, "a")
you should use the with statement. this assume that the file descriptor is closed no matter what:
with open('file', 'r') as fd:
value = int(fd.read())
with open('file', 'w') as fd:
fd.write(value + 1)
You never close the file. If you don't properly close the file the OS might not commit any changes. To avoid this problem it is recommended that you use Python's with statement to open files as it it will close them for you once you are done with the file.
with open('my_file.txt', a) as f:
do_stuff()
python open file paramters:
w:
Opens a file for writing only. Overwrites the file if the file exists.
If the file does not exist, creates a new file for writing.
You can use a (append):
Opens a file for appending. The file pointer is at the end of the file
if the file exists. That is, the file is in the append mode. If the
file does not exist, it creates a new file for writing.
for more information you can read here
One more advice is to use with:
with open("x.txt","a") as f:
data = f.read()
............
For example:
with open('c:\commentcount.txt','r') as fp:
counts = fp.readline()
counts = str(int(counts) + 1)
with open('c:\commentcount.txt','w') as fp:
fp.write(counts)
Note this will work only if you have a file name commentcount and it has a int at the first line since r does not create new file, also it will be only one counter...it won't append a new number.

Why can't I write to a file that I open in python?

I opened the python interpreter and tried to write to a file I was reading at the same time:
file = open("foo.txt")
lines = file.readlines()
for i in range(0, 3):
file.write(lines[0])
However, python issued an error that noted I had a bad file handler when I tried to execute file.write(lines[0]). Why can't I write the first line of a file to the file itself?
In order to write to a file, it's necessary to open the file in write or read/write mode
file = open("foo.txt", "r+")  # reading and writing to file
or
file = open("foo.txt", "w") # writing only to file
If you open a file and don't specify a mode, it's in read mode by default, so you had opened your file for "read", but were trying to "write" to it.
See Reading and Writing Files Python Docs for more information. #Mizuho also suggested this page about Python File IO which has a very nice summary of the various modes available.

Categories