Using the open(' ', 'w') function but file is not being edited - python

I'm using the code below to attempt to open a file and edit the text in the file (this is; my string), but after running this code, the file remains unchanged when I open it in my documents. Anyone got an idea why?
myfile=open("file","w")
mod= "this is; my string ".split(";")
myfile.write(" ".join(mod))
myfile.close()

your code will create file at the directory where the script is running. you should use:
file_path = os.path.abspath(__file__) + "/file"
f = open(file_path,"w")
f.write(.....)
f.close()
and then it will create file in the directory you want.

Try this:
with open("file","w+") as myfile: # Use mode w+
mod= "this is; my string ".split(";")
myfile.write(" ".join(mod))
using with open() as x you do not need to run .close()

Related

The following code is supposed to read a file and print the file contents to the Terminal window. It doesn’t work, I'm not sure why?

The following code is supposed to read a file and print the file contents to the Terminal window. It doesn’t work, I'm not sure why?
filename = raw_input(’Provide the path to a text file: ’)
txt = open(filename)
print txt
First, you need to use straight quotes ' instead of smart quotes ’. Second, you need to actually read the opened file with something like read().
filename = raw_input('Provide the path to a text file: ')
txt = open(filename).read()
print txt

python 2.7: Testing text file in idle

I m using the command testFile = open("test.txt") to open a simple text file and received the following: Does such errors occur due to the version of python one uses?
IOError: [Errno 2] No such file or directory: 'Test.txt
add an "a+" mode argument on to your open, this will create the file if it doesn't exist:
testFile = open("test.txt", "a+")
Syntax for opening file is:
file object = open(file_name [, access_mode][, buffering])
As you have not mentioned access_mode(optional), default is 'Read'. But if file 'test.txt' does not exists in the folder where you are executing script, it will through an error as you got.
To correct it, either add access_mode as "a+" or give full file path e.g. C:\test.txt (assuming windows system)
The error is independent from the version, but it is not clear
what you want to do with your file.
If you want to read from it and you get such an error, it means that your file is not where you think it is. In any case you should write a line like testFile = open("test.txt","r").
If you want to create a new file and write in it, you will have a line like
testFile = open("test.txt","w"). Finally, if your file already exists and you want to add things on it, use testFile = open("test.txt","a") (after having moved the file at the correct place). If your file is not in the directory of the script, you will use commands to find your file and open it.

Python script fails to read a file

I have a python script 'main.py' which calls another python script called 'getconf.py' that reads from a file 'configuration.txt'. This is what it looks like:
if __name__ == "__main__":
execfile("forprolog.py") # this creates configuration.txt
execfile("getconf.py")
When getconf.py is called via main.py it sees configuration.txt as an empty file and fails to read the string from it.
This is how I read from a file:
f1 = open("configuration.txt")
conf = f1.read() #this string appears to be empty
print f1 returns <open file 'D:\\DIPLOMA\\PLANNER\\Exe\\configuration.txt', mode 'r' at 0x01A080D0>
print f1.read() returns an empty string
I suspect the reason of the failure is that the file is being written immediately before calling getconf.py. If I run main.py when configuration.txt is already there it works. Adding a time delay between the actions doesn't solve the problem.
Would appreciate any help!
I saw other questions related to this:
Python read() function returns empty string
Try to add this line before reading:
file.seek(0)
https://stackoverflow.com/a/16374481/4733992
If this doesn't solve the problem, you can still get the lines one by one and add them to a single string:
file = open("configuration.txt", 'r')
file_data = ""
for line in file:
file_data += line
file.close()
I found my problem, it was due to the fact I didn't close the file that I was writing in. Thanks to all who tried to help.

Python's readline() function seeming not to work?

for some reason the readline() function in my following code seems to print nothing.
fileName = input()
fileName += ".txt"
fileA = open(fileName, 'a+')
print("Opened", fileA.name)
line = fileA.readline()
print(line)
fileA.close()
I'm using PyCharm, and I've been attempting to access 'file.txt' which is located inside my only PyCharm project folder. It contains the following:
Opened file!!
I have no idea what is wrong, and I can't find any relevant information for my problem whatsoever. Any help is appreciated.
Because you opened the file in a+ mode, the file pointer starts at the end of the file. After all, that is where you would normally append text.
If you want to read from the top, you need to place fileA.seek(0) just before you call readline:
fileA.seek(0)
line = fileA.readline()
Doing so sets the pointer to the top of the file.
Note: After reading the comments, it appears that you only need to do this if you are running a Windows machine. Those using a *nix system should not have this problem.

Missing file when using Python 2.7.3 File.write() function

If you are simply planning to write to a file using a python script as show below:
#!/usr/bin/python
count = 1
fo = open('DbCount.txt', 'w')
fo.write(str(count))
#fo.flush()
fo.close()
The Dbcount.txt file which was placed in the same folder as the script(attempting to modify the Dbcount.txt). i dont see any change in the txt file and no error is shown by the interpreter, its very strange, any help ?
first of all, always use the with statement variant, that will always close the file, even on errors:
#!/usr/bin/python
count = 1
with open('DbCount.txt', 'w') as fo:
fo.write(str(count))
then the 'w' overwrites your file each time you write to it. If you want to append, use 'a'.
About your specific problem, did you look only in the directory of your script, or in the current directory you're calling the script from? As you wrote your code, the file's path you write to is relative to where you execute your code from.
try:
import os
count = 1
with open(os.path.join(os.path.dirname(__file__), 'DbCount.txt'), 'w') as fo:
fo.write(str(count))
then it should output DbCount.txt in the same path as your script.

Categories