create a file in the script using python - python

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:

Related

How Can I Make A Working .py File Within a Python File?

I am trying to make the file py.py within this code
def makeFile():
contents = "import JustIRC\nimport requests";
file = open('py.py');
file.write(contents);
file.close();
But if I run it it returns io.UnsupportedOperation: not writable What is the problem and how can I fix it? I need to be able to specifically tab and newline for the program to run correctly
You need to open the file with the write option:
file = open("py.py", "w")
It depends how you want to use that file:
file = open('py.py', 'w') - create the file if it doesn't exist and write to it. If the file exists, delete everything from it and write the new content
file = open('py.py', 'a') - create the file if it doesn't exists. If the file exists, keep the content and write at the end

Program running but file not opening using open() function

I am just learning about file manipulation and created a simple 'text.txt' file. This file, as well as my source code('files.py') share the same parent directory('files/'). I am trying to open the file:
import os
helloFile = open('./text.txt')
However, when I run this at the command line no error is thrown but no file is opened. It seems like it is running with no problem but not doing what I want it to do. Anyone know why?
Well, you should probably read() from file as you only created file descriptor object which targets the file, but didn't really do any operation on it.
also, I recommend you to use
with open('./text.txt') as f:
helloFile = f.read()
it will automatically close file for you,
in other case you need to close file manually like below:
f = open('./text.txt')
helloFile = f.read()
f.close()

How to save multiple values to a file in python

So I would like to know how to save and check different values in a file. I have tried to read a file
with open(filename, 'r') as f:
varName = f.readline()
and this to write things to a file however this overwrites anything already in the file
with open('topname.txt', 'w') as f:
f.write(str(name))
f.close()
another problem is when I want to check the values by using a for loop however that didn't work. I was wondering if there was any other way to check, read and write values to/from a file.
An example of this is a login page where people can make accounts and log in and the program checks if the username and password exist.
When I looked on the internet it talked about a thing called pickle but it wasn't the same thing as what I wanted from what I could see.
For your first question, you need to open the file in append mode:
with open('topname.txt', 'a+') as f:
f.write(str(name))
f.close()
The '+' sign in append mode indicates that the script will create a new file if it doesn't already exist, if it does, it'll just append to it.
You want to "append" to the file, so open it with mode 'a' instead of 'w'.
Also, do not call f.close() inside of the with block. with will close the file for you after the block.
with open('topname.txt', 'a') as f:
f.write(str(name))
See: https://docs.python.org/3.6/library/functions.html#open
To append data to an existing file use open("Filename", "a") for "append mode." This is in contrast to your "read" and "write" modes.
if you want to read ,write and update, you need to open file file = open('topname.txt', 'a+') and to check every line to match user data for line in file:print(line) .Other operations like file.read(), file.write() will help. Remember to release resources by closing file finally file.close()

Python Subprocess for Notepad

I am trying to open Notepad using popen and write something into it. I can't get my head around it. I can open Notepad using command:
notepadprocess=subprocess.Popen('notepad.exe')
I am trying to identify how can I write anything in the text file using python. Any help is appreciated.
You can at first write something into txt file (ex. foo.txt) and then open it with notepad:
import os
f = open('foo.txt','w')
f.write('Hello world!')
f.close()
os.system("notepad.exe foo.txt")
You may be confusing the concept of (text) file with the processes that manipulate them.
Notepad is a program, of which you can create a process. A file, on the other hand, is just a structure on your hard drive.
From a programming standpoint, Notepad doesn't edit files. It:
reads a file into computer memory
modifies the content of that memory
writes that memory back into a file (which could be similarly named, or otherwise - which is known as the "Save as" operation).
Your program, just as any other program, can manipulate files, just as notepad does. In particular, you can perform exactly the same sequence as Notepad:
my_file= "myfile.txt" #the name/path of the file
with open(file, "rb") as f: #open the file for reading
content= f.read() #read the file into memory
content+= "mytext" #change the memory
with open(file, "wb") as f: #open the file for writing
f.write( content ) #write the memory into the file
Found the exact solution from Alex K's comment. I used pywinauto to perform this task.

python clear csv file

how can I clear a complete csv file with python. Most forum entries that cover the issue of deleting row/columns basically say, write the stuff you want to keep into a new file. I need to completely clear a file - how can I do that?
Basically you want to truncate the file, this can be any file. In this case it's a csv file so:
filename = "filewithcontents.csv"
# opening the file with w+ mode truncates the file
f = open(filename, "w+")
f.close()
Your question is rather strange, but I'll interpret it literally. Clearing a file is not the same as deleting it.
You want to open a file object to the CSV file, and then truncate the file, bringing it to zero length.
f = open("filename.csv", "w")
f.truncate()
f.close()
If you want to delete it instead, that's just a os filesystem call:
import os
os.remove("filename.csv")
The Python csv module is only for reading and writing whole CSV files but not for manipulating them. If you need to filter data from file then you have to read it, create a new csv file and write the filtered rows back to new file.

Categories

Resources