I am trying to build a program that reads a value from a separate text file. In this case, it is named "Test.lang". It contains the text "Hello World".
My program was working just fine with:
from sys import *
def open_file(filename):
print (filename)
def run():
data = open_file(argv[1])
run()
Then, when I tried to change it to:
from sys import *
def open_file(filename):
data = open(filename, "r").read()
print (data)
def run():
data = open_file(argv[1])
run()
It does not work. I get 4 errors:
Traceback (most recent call last):
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 10, in <module>
run()
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 8, in run
data = open_file(argv[1])
File "C:\Users\John\Desktop\Senior Project\basic.py
", line 4, in open_file
data = open(filename, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'test.lang'
What is really confusing me is the last one. How did the previous program work, but now test.lang doesn't exist?
Please help me.
Here is how you do this.
To read a file:
file = open('Directory Of The File.txt', 'r')
MyVariable = file.read()
file.close()
To write a file:
file = open('Directory Of The File.txt', 'w')
file.write('Insert Text, Variable or Other Data Here!')
file.close()
It's as easy as that!
You can change the .txt for .lang or any other supported file extension!
Please reply and let me know if this worked for you :)
Related
Foundation year programming student here. I'm trying to do some batch mode processing, Taking a list of names in a file, opening said file, reading it, assigning a username each name in the file and then storing said names in another file.
Here is my code:
# A program which takes a list of names from a file, creates a new file
# and makes a username based on each name into it.
#first open each file
import string
def main():
infileName = raw_input("What file are the names in")
outfileName = raw_input("What file are the usernames going in?")
#open the files
infile = open(infileName, "r")
outfile = open(outfileName, "w")
data = infile.read()
print data
main()
#process each line in the file
for line in infile:
#get the first and last names from line
first, last = string.split(line)
#create a username
uname = string.lower(first[0]+last[:7])
#write it to output file
outfile.write(uname+"\n")
#close both files
infile.close()
outfile.close()
print "The usernames have been written to, ", outfileName
It all seems fine except it comes out with the error code:
Traceback (most recent call last):
File "C:/Users/Manol/OneDrive/Documents/Uni/Programming/File Processing File/BatchUsernames.py", line 23, in <module>
for line in infile:
NameError: name 'infile' is not defined
>>>
I don't understand as I thought I had defined it on line 13
infile = open(infileName, "r")
If anyone could point out what I'm doing wrong it would be much appreciated.
Thanks for you time
Manos
You defined it in your main() function, so it is a local variable. Any function outside of main() won't recognize it. You should probably also use data instead but again, that is a local variable. A possible solution could be something like this:
import string
def main():
infileName = raw_input("What file are the names in")
outfileName = raw_input("What file are the usernames going in?")
#open the files
infile = open(infileName, "r")
outfile = open(outfileName, "w")
data = infile.read()
for line in data:
first, last = string.split(line)
uname = string.lower(first[0]+last[:7])
outfile.write(uname+"\n")
infile.close()
outfile.close()
print(data)
print("The usernames have been written to, ", outfileName)
main()
Im working on a saving system for user names right now. The current variable looks like this: name = input("What is your name"). I have it writing out to a text file.
I tried setting name as a variable without the input, and tried making the input the write function (idk why). No luck with either of those.
def welcome():
os.system('cls' if os.name == "nt" else 'clear')
print(color.color.DarkGray + "Welcome...")
sleep(5)
name = input("Enter Name Here: ")
name1 = name
saveUserInp = open("userNames.txt", 'w')
with open ("userNames.txt") as f:
f.write(name)
sleep(5)
print("Welcome",name1)
sleep(5)
menu()
Provided above is the code for the welcome function.
Traceback (most recent call last):
File "main.py", line 54, in <module>
welcome()
File "main.py", line 21, in welcome
f.write(name)
io.UnsupportedOperation: not writable
Provided is the actual error given. Line 54 is calling the welcome function, which breaks after I type in my name. Like 21 is the f.write function. I am not sure why it doesn't want to write it into the file.
You should open the file specifying the open mode if it's different than read:
with open ("userNames.txt", "w") as f:
f.write(name)
open with no mode provided opens the file in read mode by default, no surprise it's not writable.
By the way, what's the point of opening the file twice? Lines
saveUserInp = open("userNames.txt", 'w')
...
saveUserInp.close()
might be removed since you open file with the with statement.
i am getting some errors that i cant figure out how to fix with the below program, here is the instructions for it.
"Write a program that prompts for two file names and exchanges the contents of the two files. Your program should be sufficiently robust that if a file doesn't exist, the program will re-prompt."
below is the error i get when i am trying to run it. I also evidently still need to make it re-prompt for the user if the files cant is found. I tried a few things to get it to work but was unable to get it to work properly for that as well.
Traceback (most recent call last):
File "C:\Users\istal\Desktop\6.2.py", line 30, in <module>
dataobject.transfer(firstfilename,secondfilename)
File "C:\Users\istal\Desktop\6.2.py", line 5, in transfer
with open(firstfilename,'r')as filedata:
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/istal/Desktop/python/testone.tx'
here is the code itself
class DataTransferinFiles():
def transfer(self,firstfilename,secondfilename):
print("your first file is=",firstfilename);
print("your second file is =", secondfilename)
with open(firstfilename,'r')as filedata:
firstfiledata= filedata.readlines()
print()
print("1st file reading complete")
print()
with open(secondfilename, 'r')as filedata:
secondfiledata=filedata.readlines()
print("2st file reading complete")
for eachline in firstfiledata:
filesecond = open(secondfilename,'a')
filesecond.write("/n"+eachline+ "/n")
print ("1st file transfered in to second file")
for eachline in secondfiledata:
filefirst = open(firstfilename)
filefirst.write("\n"+eachline+ "\n")
print ("second file transfered in to first file")
dataobject = DataTransferinFiles()
firstfilename = input("enter first file name for transfer")
secondfilename = input("enter second file name for transfer")
dataobject.transfer(firstfilename,secondfilename)
It's an typo, of the indentation.
The line:
dataobject = DataTransferinFiles()
Should be just:
dataobject = DataTransferinFiles()
So the full code:
class DataTransferinFiles():
def transfer(self,firstfilename,secondfilename):
print("your first file is=",firstfilename);
print("your second file is =", secondfilename)
with open(firstfilename,'r')as filedata:
firstfiledata= filedata.readlines()
print()
print("1st file reading complete")
print()
with open(secondfilename, 'r')as filedata:
secondfiledata=filedata.readlines()
print("2st file reading complete")
for eachline in firstfiledata:
filesecond = open(secondfilename,'a')
filesecond.write("/n"+eachline+ "/n")
print ("1st file transfered in to second file")
for eachline in secondfiledata:
filefirst = open(firstfilename)
filefirst.write("\n"+eachline+ "\n")
print ("second file transfered in to first file")
dataobject = DataTransferinFiles()
firstfilename = input("enter first file name for transfer")
secondfilename = input("enter second file name for transfer")
dataobject.transfer(firstfilename,secondfilename)
I'm seeing a couple of issues.
In the for eachline in... blocks you are trying to reopen files that you have not closed. Add a with when you open them to write, the same way that you used the with context manager for the first. Otherwise you're trying to open the file every time you write a line.
The for eachline in secondfiledata does not append like the first does -- so if you were successfully closing the file, you'd just keep overwriting until the final line.
You're overcomplicating this by using readlines() instad of read().
This assumes that you are reading and writing text in the files. What if it's a binary file?
I recommend perusing https://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files
print "Which category would you like to view? Savory, Dessert, Cake, Soup or Drink? "
category = raw_input()
for x in os.listdir(category): print x
name = raw_input("Which recipe would wou like to view? ")
fullname = os.path.join(category, name)
f = open(fullname, "r");
print f
I am writing a program that will allow users to view the contents of .txt files saved in specific directories. When I run this code I don't get the contents and instead get a message that says this:
open file 'savory/b.txt', mode 'r' at 0x1004bd140
any ideas. I am new to python so i dont have much of an idea as to what is causing the error but i assume it is due to some missing code.
Thank you.
The return value of open is a file object (not the file contents!) .You need to call a method on your file object to actually read the file:
f = open(fullname, "r")
print f.read()
f.close()
If it's a big file you may want to iterate over the file line-by-line
f = open(fullname, "r")
for line in f:
print line
f.close()
On a side note, here's alternate syntax to you don't have to remember to call the close method:
with open(fullname, "r") as f:
for line in f:
print line
im trying to create a script that opens a file and replace every 'hola' with 'hello'.
f=open("kk.txt","w")
for line in f:
if "hola" in line:
line=line.replace('hola','hello')
f.close()
But im getting this error:
Traceback (most recent call last):
File "prueba.py", line 3, in
for line in f: IOError: [Errno 9] Bad file descriptor
Any idea?
Javi
open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello'))
Or if you want to properly close the file:
with open('test.txt', 'r') as src:
src_text = src.read()
with open('test.txt', 'w') as dst:
dst.write(src_text.replace('hola', 'hello'))
Your main issue is that you're opening the file for writing first. When you open a file for writing, the contents of the file are deleted, which makes it quite difficult to do replacements! If you want to replace words in the file, you have a three-step process:
Read the file into a string
Make replacements in that string
Write that string to the file
In code:
# open for reading first since we need to get the text out
f = open('kk.txt','r')
# step 1
data = f.read()
# step 2
data = data.replace("hola", "hello")
f.close()
# *now* open for writing
f = open('kk.txt', 'w')
# step 3
f.write(data)
f.close()
You've opened the file for writing, but you're reading from it. Open the original file for reading and a new file for writing. After the replacement, rename the original out and the new one in.
You could also have a look at the with statement.