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.
Related
so first and foremost i wanted to connect multiple lines into one and add ","
so in example
line1
line2
line2
to
line1,line2,line3
i managed to make it work with this script right here
filelink = input("Enter link here ")
fix = file = open(filelink, "r")
data=open(filelink).readlines()
for n,line in enumerate(data):
if line.startswith("line"):
data[n] = "\n"+line.rstrip()
else:
data[n]=line.rstrip()
print(','.join(data))
HOWEVER in the terminal itself it shows it executed perfectly but in the text file itself it's still remains the same no connected lines and no commas
side note. i would love some explanations how does the loop work and what "enumerate" stands for and why specifically this code i tried googling each one separately and understand the code but i didn't manage to find what i was looking for if anyone keen to explain the code line by line shortly i would be very appreciative
Thanks in advance <3
This is somewhat superfluous:
fix = file = open(filelink, "r")
That's assigning two names to the same file object, and you don't even use fix, so at least drop that part.
For handling files, you would be better using a context manager. That means that you can open a resource and they will automatically get closed for you once you're done (usually).
In any case, you opened in read mode with open(filelink, "r") so you'll never change the file contents. print(','.join(data)) will probably show you what you expect, but print() writes to stdout and the change will only be in your terminal. You will not modify the base file with this. But, I think you're sufficiently close that I'll try close the missing connection.
In this case, you need to:
open the file first in read mode to pull the data out.
Do the transform in python to the data
Open the file again in write mode (which wipes the existing contents)
Write the transformed data
So, like this:
filelink = input("Enter link here ")
with open(filelink) as infile: # context manager, by default in "r" mode
data = [item.strip() for item in infile.readlines()]
data = ','.join(data)
# Now write it back out
with open(filelink, "w") as outfile:
outfile.write(data)
So I am trying to add save files to my text-adventure game that can't be edited by the user. This is so that they can't cheat by editing the dictionary inside of it. So far all I've done is a few algorithms that can be easily bypassed if you connected the dots. Basically it's this.
import sys,os,ast
dictionary = {...}
save_dictionary = {...}
def save():
filehandler = open("dictionary.txt", "a")
data = str(dictionary)
filehandler.write(data)
filehandler.close()
def savecode():
savecode = dictionary.values()
total = sum(savecode)
save_dictionary['savecodes'] = round(math formulas)
filehandler = open("save_dictionary.txt", "a")
data = str(save_dictionary)
filehandler.write(data)
filehandler.close()
def load():
with open('dictionary.txt') as f:
data = f.read()
save = ast.literal_eval(data)
f.close()
But the problem I'm facing is that it is easily by-passible if you just add an amount and equally subtract an amount, which would make the sum the same, making everything work the same. I did make it so that anytime the game itself detects any changes it immediately deletes all save files and makes you start over.
So is the solution making the files unable to be accessed at all? Or is it that the python file will detect the time it was created? I have no idea. It could be another option.
You can't hide files from the super user. They bought their computer and they reserve the right to read and edit whatever files they please. And no program will ever have higher permissions than the administrator.
Your best bet is to encrypt the data inside the file. So that if the user tries to edit, the program won't function properly.
A question that might be more relevant:
https://gamedev.stackexchange.com/questions/48629/how-do-i-prevent-memory-modification-cheats
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.
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.
What I'm trying to do is to ask a user for a name of a file to make and then save some stuff in this file.
My portion of the program looks like this:
if saving == 1:
ask=raw_input("Type the name file: ")
fileout=open(ask.csv,"w")
fileout.write(output)
I want the format to be .csv, I tried different options but can't seem to work.
The issue here is you need to pass open() a string. ask is a variable that contains a string, but we also want to append the other string ".csv" to it to make it a filename. In python + is the concatenation operator for strings, so ask+".csv" means the contents of ask, followed by .csv. What you currently have is looking for the csv attribute of the ask variable, which will throw an error.
with open(ask+".csv", "w") as file:
file.write(output)
You might also want to do a check first if the user has already typed the extension:
ask = ask if ask.endswith(".csv") else ask+".csv"
with open(ask, "w") as file:
file.write(output)
Note my use of the with statement when opening files. It's good practice as it's more readable and ensures the file is closed properly, even on exceptions.
I am also using the python ternary operator here to do a simple variable assignment based on a condition (setting ask to itself if it already ends in ".csv", otherwise concatenating it).
Also, this is presuming your output is already suitable for a CSV file, the extension alone won't make it CSV. When dealing with CSV data in general, you probably want to check out the csv module.
You need to use ask+'.csv' to concatenate the required extension on to the end of the user input.
However, simply naming the file with a .csv extension is not enough to make it a comma-separated file. You need to format the output. Use csvwriter to do that. The python documentation has some simple examples on how to do this.
I advise you not to attempt to generate the formatted comma-separated output yourself. That's a surprisingly hard task and utterly pointless in the presence of the built-in functionality.
Your variable ask is gonna be of type string after the raw_input.
So, if you want to append the extension .csv to it, you should do:
fileout = open(ask + ".csv", "w")
That should work.