I want to rename a normal .txt file to .my_extension, not change its structure or anything.
Can I make python read that .my_extension as a .txt so it can read/write to it?
This line of code will treat the custom extension file as a txt file and write to it.
File = open('File_Name.custom_extention', 'w').write('Text')
Same goes with reading. Python actually does not look at the file extension.
But if you'd try to write to a file with a file structure of an exec it probably won't work :)
of course
actually python and almost every other language do not treat files by looking at the extension
they just do what you want
you can even have files with no extension and that's Ok
you can open a file just like this:
f = open('filename', 'mode')
to open a file
note that 'filename' should be the full name of file and the extension
somthing like 'myfile.myextension'
then write text into it like this
f.write('text to write in file')
see the list of modes in here
Yes you can work with opening and closing files and writing ,reading etc..
with this line of code :
output_file = open("your_file_name",mode="r")
the mode can specify the mode that you open the file for example if you want only open a file for reading type "r" ,for writing type "w",for appending type "a".
NOTE:
After opening the file in python you must close it by the close() statement (this may cause data leaking).
ex:
output_file.close()
Related
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
I have this .log file that I changed the extension name into .txt file but it still reads as log file
but after I copied it and paste it a new editor and saved it as .txt file.. this is what it showed:
Somebody told me that it is a non-ASCII characters that I should delete. Is there any way to delete it or any way to copy the contents of a log file then place it in a text file using python?
In Python you can specify the input encoding.
with open('trendx.log', 'r', encoding='utf-16le') as reader, \
open('trendx.txt', 'w') as writer:
for line in reader:
if "ROW" in line:
writer.write(line)
I have obviously copied over some stuff from your earlier questions. Kudos for finally identifying the actual problem.
Notice in particular how we avoid reading the entire file into memory and instead processing a line at a time.
I have a text file that I created using
open(new_file_name_string,"w+")
I want to know if/how I can use the open function (or any other python function) to create a python (.py) file instead of a text (.txt) file. For instance, can I use a different argument than "w+" to make open generate a python file?
If there is nothing like this available, is there a python function that can convert my .txt file into a .py file?
if you mean that you want to change the extension, just change the filename. If your previous filename is just filename or filename.txt just change it to filename.py
I'm writing a simple parser. For now, it reads the whole current dir and open files with 'r' and 'w' permissions for all files that end with ".w". Here's the code for it:
import os
wc_dir = os.path.dirname(os.path.abspath(__file__))
files = [f for f in os.listdir(wc_dir) if os.path.isfile(os.path.join(wc_dir,f))]
comp_files_r = [open(f, 'r') for f in files if f.endswith(".w")]
comp_files_w = [open(f, 'w') for f in files if f.endswith(".w")]
As you can see, I have two lists with "open objects" with read and write permissions for all files in the current folder that end with ".w". For now, I have just one file. So, consider the following:
print comp_files_r
print comp_files_w
Output:
[<open file 'app.w', mode 'r' at 0x7effd48274b0>]
[<open file 'app.w', mode 'w' at 0x7effd4827540>]
It happens that, when I try to read the 'app.w' file:
def parse():
for f in comp_files_r:
with f as file:
data = file.read()
print repr(data)
parse()
I get an astonishing empty string for no reason. I've managed to discover that, all that I save in 'app.w' gets erased when I execute the code with the "w list comprehension". So why is that? I've learned from pain that trying to both read and write a file in "r+" mode can lead to weird results. That's not the situation. I've created different objects from the same file, and this is messing with the content of the file itself. Why?
It looks to me that your issue is that you're opening the file in 'w' mode. When you open a file in 'w' mode, the current file is deleted and replaced with the new file. 'r+' mode is for reading and editing.
I'd be willing to bet that if you read the contents of the files between the lines where you open them for reading and and the line where you open them for writing, you will see the contents of the files as you expect them to be.
I am new to python.
I wanted to know if I could create a text file in the script itself before writing into.
I do not want to create a text file using the command prompt.
I have written this script to write the result into the file
with open('1.txt', 'r') as flp:
data = flp.readlines()
however I know that 1.txt has to be created before writing into it.
Any help would be highly appreciated.
Open can be used in a several modes, in your case you have opened in read mode ('r'). To write to a file you use the write mode ('w').
So you can get a file object with:
open('1.txt', 'w')
If 1.txt doesn't exist it will create it. If it does exist it will truncate it.
You can use open() to create files.
Example:
open("log.txt", "a")
This will create the file if it doesn't exist yet, and will append to it if the file already exists.
Using open(filename, 'w') creates the file if it's not there. Be careful though, if the file exists it will be overritten!
You can read more details here: