Python not creating simple txt file by using "write" - python

I wrote this simple code and no text file was created. I also tried to create it manually in the same folder and append something on and that also didn't work.
employee_file = open("employees.txt" , "w")
employee_file.write("toby human resources")
employee_file.close()

You should really put the code in the question. After some time the image will probably be deleted and many people won't be able to benefit from your question.
Try the following code:
import os
print (os.getcwd())
employee_file = open("employees.txt" , "w")
employee_file.write("toby human resources")
employee_file.close()
It should print the current working directory, where the file should be saved.

Firstly - your code is correct.
Secondly - why not use "built-in" statements (which closes the file so we don't have take care of it)
with open('employees.txt','w') as file:
file.write("some data")
# do sth else ...
and we don't have to close the file here.

Related

Files are not opening nor writing through python code

Completely new and learning python, so please be patient with my noob problems lol.
i tried entering this code:
file = open('Test.txt','w')
file.write('Hello world')
After that it doesn't give me an error but also wont open nor write. The Text.txt file is on my desktop and i tried direct path but also same problem. could i be missing something? Thank you in advance.
your file is not where you think it is try changing to this
print(os.getcwd())
file = open('Test.txt','w')
file.write('Hello world')
print("Wrote : {0}".format(os.path.abspath("Test.txt")))
print("Contents: ",open("Test.txt","r").read())
as an aside when opening for writing you should really use a filecontext
with open("Test.txt","w") as f:
f.write('Hello world')
this ensures the file is properly closed afterwards
my observations are as under.
1. After the second line of code , Python returns the no. of characters written into the file, in your case 11. Have you observed it?.
2. Although you may see your file using file explorer on your desktop, you won't see any thing written in it if you open it using notepad. For you to see the contents you wrote, you need to close the file by file.close() in python.
3. The file name is test.txt as you mentioned, but you have stated 'Text.txt' is on desktop. Pl. reconcile.
best regards
NR

Is It Possible to Make a File with a Function in Python?

I am trying to make a file with a function in python, but I have no idea how. This is what I have, and what I need.
def file_maker():
file_number = input("What number player are you? ")
#Insert however you make a file in code, naming it ('inventory.' + filenumber + '.txt')
I only need to know how I would initiate the file-making process. I tried googling it, but the only thing that comes up is how to access a function within a different file. I am an amateur programmer, any and all suggestions are welcome. Thanks for your time.
def file_maker():
file_number = input("What number player are you? ")
with open("inventory.%s.txt" % file_number, "w") as f:
# Do whatever you need with the file using the 'f' to refer to the file object
pass # in case you don't want to do anything with the file, but just create it
Read more regarding open function here: Open function
FYI, this will overwrite the file if it already exists.
To create a file, just open in it write mode.
file_handle=open ('inventory.' + filenumber + '.txt', "w")
file_handle is now an object that you can use various methods on to add content to the file. Read the documentation here.
Make sure you close the file when you are done with it using file_handle.close()
Note: Although this method works, it is usually considered better practice to use with, as shown in the other answer. It uses less code and automatically closes the file when done.

How to store a txt file in your program and reference it

Let me preface by saying I am very new to programming. I'm creating a fun program that I can use to start my day at work. One of the things I want it to do is display a random compliment. I made a text file that has multiple lines in it. How do I store that text file then open it?
I've opened text files before that were on my desktop but I want this one to be embedded in the code so when I compile the program I can take it to any computer.
I've googled a ton of different key words and keep finding the basics of opening and reading txt files but that's not exactly what I need.
Perhaps start with defining a default path to your file; this makes it easier to change the path when moving to another computer. Next, define a function in your program to read and return the contents of the file:
FILE_PATH = "my/path/to/file/"
def read_file(file_name):
with open(FILE_PATH + file_name) as f:
return f.read()
With that in place, you can use this function to read, modify, or display the file contents, for example to edit something from your file:
def edit_comments():
text = read_file("daily_comments.txt")
text = text.replace("foo", "foo2")
return text
There are obviously many ways to approach this task, this is just a simple example to get you started.

Python writing data to file only works when run from console

If I run
file = open("BAL.txt","w")
I = '200'
file.write(I)
file.close
from a script, it outputs nothing in the file. (It literally overwrites the file with nothing)
Furthermore, running cat BAL.txt just goes to the next line like nothing is in the file.
But if I run it line by line in a python console it works perfectly fine.
Why does this happen. ( I am a begginner learning python the mistake may be super obvious. I have thrown about 2 hours into trying to figure this out)
Thanks in advance
You aren't closing your file properly. To close it you are missing the () at the end of file.close so it should look like this:
file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()
This site has the same example and may be of some use to you.
Another way, especially useful when you are appending multiple values into a single file is to use something like with open("BAL.txt","w") as file:. Here is your script rewritten to include this example:
I = '200'
with open("BAL.txt","w") as file:
file.write(I)
This opens our file with the value file and allows us to write values to it. Also note that file.close() is not needed here and when appending text w+ needs to be used.
to write to a file you do this:
file = open("file.txt","w")
file.write("something")
file.close()
when you use file.write() it deletes all of the contents of the file, if you want to write to the end of the file do this:
file = open("file.text","w+")
file.write(file.read()+"something")
file.close()
There are other ways to do this but this one is the most intuitive (not the most efficient), also the other way tends to be buggy so there is no reason to post it because this is reliable.
Firstly, you're missing the parentheses when you're closing the file. Secondly, writing to a file should be done like this:
file = open("BAL.txt", "w")
file.write("This has been written to a file")
file.close()
Let me know if you have any questions.

What is the most pythonic way to open a file?

I'm trying to clean up my code a little bit, and I have trouble figuring which of these 2 ways is considered the most pythonic one
import os
dir = os.path.dirname(__file__)
str1 = 'filename.txt'
f = open(os.path.join(dir,str1),'r')
Although the second seems to be cleanest one, I find the declaration of fullPath a bit too much, since it will only be used once.
import os
dir = os.path.dirname(__file__)
str1 = 'filename.txt'
fullPath = os.path.join(dir,str1)
f = open(fullPath,'r')
In general, is it a better thing to avoid calling functions inside of another call, even if it adds a line of code ?
with open('file path', 'a') as f:
data = f.read()
#do something with data
or
f = open(os.path.join(dir,str1),'r')
f.close()
file = open('newfile.txt', 'r')
for line in file:
print line
OR
lines = [line for line in open('filename')]
If file is huge, read() is definitively bad idea, as it loads (without size parameter), whole file into memory.
If your file is huge this will cause latency !
So, i don't recommend read() or readlines()
There are many ways to open files in python which goes to say that there really isn't really a pythonic way of doing it. It all just boils down to which method you see are most connivence, especially in regards to what you're actually trying to do with the file once its open.
Most users use the IDLE GUI "click" to open files because it allows them to view the current file and also make some alterations if there's a need for such.
Others might just rely on the command lines to perform the task, at the cost of not being able to do anything other than opening the file.
Using Command Lines:
% python myfile.py
note that in order for this to work you need to make sure the system is "looking" into the directory where your file is storied. Using the 'cd' is useful to finding you route there.
% python import myfile myfile.title
This method is known as the object.attribute method of opening files. This method is useful when the file you're opening has an operation that you would like to implement.
There are more ways than what's been stated above, be sure to consult the pyDocs for further details.

Categories