def readfile(file):
edges = [] # to contain tuples of all edges
with open(file) as f:
for line in f:
I'm trying to pass in a text file called file, then read it, but it doesn't work. Even if I cast file to a string it doesn't work.
Python says
with open(file) as f: IOError: [Errno 22] invalid mode ('r') or
filename: "<type 'file'>"
How do I open a file, passed to open as a variable?
Rename file by filename as file is a built-in name for python :
def readfile(filename):
edges = [] # to contain tuples of all edges
with open(filename) as f:
for line in f:
open() use 'r' as default mode.
First of all , as file is a type in python you shouldn't use it as a variable name or file name , second you need to put the file name in quote inside the open function and note that open function use read mod as default ! :
with open('file_name.txt','r') as f:
for line in f:
Related
how do you do this series of actions in python?
1) Create a file if it does not exist and insert a string
2) If the file exists, search if it contains a string
3) If the string does not exist, hang it at the end of the file
I'm currently doing it this way but I'm missing a step
EDIT
with this code every time i call the function seems that the file does not exist and overwrite the older file
def func():
if not os.path.exists(path):
#always take this branch
with open(path, "w") as myfile:
myfile.write(string)
myfile.flush()
myfile.close()
else:
with open(path) as f:
if string in f.read():
print("string found")
else:
with open(path, "a") as f1:
f1.write(string)
f1.flush()
f1.close()
f.close()
Try this:
with open(path, 'a+') as file:
file.seek(0)
content = file.read()
if string not in content:
file.write(string)
seek will move your pointer to the start, and write will move it back to the end.
Edit:
Also, you don't need to check the path.
Example:
>>> f = open('example', 'a+')
>>> f.write('a')
1
>>> f.seek(0)
0
>>> f.read()
'a'
file example didn't exist, but when I called open() it was created. see why
You don't need to reopen the file if you have not yet closed it after initially opening it. Use "a" when opening the file in order to append to it. So... "else: with open(path, "a") as f: f.write(string)". Try that
This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 3 years ago.
I am trying to display my python file in html and therefore I would like to replace every time the file jumps to a newline with < br> but the program I've written is not working.
I've looked on here and tried changing the code around a bit I have gotten different results but not the ones I need.
with open(path, "r+") as file:
contents = file.read()
contents.replace("\n", "<br>")
print(contents)
file.close()
I want to have the file display < br> every time I have a new line but instead the code dosen't change anything to the file.
Here is an example program that works:
path = "example"
contents = ""
with open(path, "r") as file:
contents = file.read()
new_contents = contents.replace("\n", "<br>")
with open(path, "w") as file:
file.write(new_contents)
Your program doesn't work because the replace method does not modify the original string; it returns a new string.
Also, you need to write the new string to the file; python won't do it automatically.
Hope this helps :)
P.S. a with statement automatically closes the file stream.
Your code reads from the file, saves the contents to a variable and replaces the newlines. But the result is not saved anywhere. And to write the result into a file you must open the file for writing.
with open(path, "r+") as file:
contents = file.read()
contents = contents.replace("\n", "<br>")
with open(path, "w+") as file:
contents = file.write(contents)
there are some issues in this code snippet.
contents.replace("\n", "<br>") will return a new object which replaced \n with <br>, so you can use html_contents = contents.replace("\n", "<br>") and print(html_contents)
when you use with the file descriptor will close after leave the indented block.
Try this:
import re
with open(path, "r") as f:
contents = f.read()
contents = re.sub("\n", "<br>", contents)
print(contents)
Borrowed from this post:
import tempfile
def modify_file(filename):
#Create temporary file read/write
t = tempfile.NamedTemporaryFile(mode="r+")
#Open input file read-only
i = open(filename, 'r')
#Copy input file to temporary file, modifying as we go
for line in i:
t.write(line.rstrip()+"\n")
i.close() #Close input file
t.seek(0) #Rewind temporary file to beginning
o = open(filename, "w") #Reopen input file writable
#Overwriting original file with temporary file contents
for line in t:
o.write(line)
t.close() #Close temporary file, will cause it to be deleted
I am trying to create a to-do list application, and to store the users tasks, I'm writing them by line to a plaintext file. At multiple points I "sync" it by calling foo.readlines(), but even if I hand write test data into the file, the list returns empty and the contents of the plain text file are erased.
I tried opening the file manually and writing to it and saving it, but after running the script, it is again empty and the list returns empty.
import numpy as np
file = open('./data.txt', 'w+')
tasks = file.readlines()
print(tasks)
#writes list to a file
def writeFile(tasks):
with open('data.txt', 'w') as filehandle:
for listitem in tasks:
filehandle.write('%s\n' % listitem)
You're opening the file in write mode with "w+" at line 3. That deletes the file's contents.
You probably meant to use "r" instead of "w" in
with open('data.txt', 'w') as filehandle:
'Read' mode is the default mode if none specified
file = open('data.txt')
Opening a file in 'Read' mode
file = open('data.txt', 'r')
Opening a file in 'Write' mode (will overwrite the contents of the file if exists)
file = open('data.txt', 'w')
Opening a file in 'Append' mode (will append to the existing file without overwriting)
file = open('data.txt', 'a')
I have a file that I open and i want to search through till I find a specific text phrase at the beginning of a line. I then want to overwrite that line with 'sentence'
sentence = "new text" "
with open(main_path,'rw') as file: # Use file to refer to the file object
for line in file.readlines():
if line.startswith('text to replace'):
file.write(sentence)
I'm getting:
Traceback (most recent call last):
File "setup_main.py", line 37, in <module>
with open(main_path,'rw') as file: # Use file to refer to the file object
ValueError: must have exactly one of create/read/write/append mode
How can I get this working?
You can open a file for simultaneous reading and writing but it won't work the way you expect:
with open('file.txt', 'w') as f:
f.write('abcd')
with open('file.txt', 'r+') as f: # The mode is r+ instead of r
print(f.read()) # prints "abcd"
f.seek(0) # Go back to the beginning of the file
f.write('xyz')
f.seek(0)
print(f.read()) # prints "xyzd", not "xyzabcd"!
You can overwrite bytes or extend a file but you cannot insert or delete bytes without rewriting everything past your current position.
Since lines aren't all the same length, it's easiest to do it in two seperate steps:
lines = []
# Parse the file into lines
with open('file.txt', 'r') as f:
for line in f:
if line.startswith('text to replace'):
line = 'new text\n'
lines.append(line)
# Write them back to the file
with open('file.txt', 'w') as f:
f.writelines(lines)
# Or: f.write(''.join(lines))
You can't read and write to the same file. You'd have to read from main_path, and write to another one, e.g.
sentence = "new text"
with open(main_path,'rt') as file: # Use file to refer to the file object
with open('out.txt','wt') as outfile:
for line in file.readlines():
if line.startswith('text to replace'):
outfile.write(sentence)
else:
outfile.write(line)
Not the problem with the example code, but wanted to share as this is where I wound up when searching for the error.
I was getting this error due to the chosen file name (con.txt for example) when appending to a file on Windows. Changing the extension to other possibilities resulted in the same error, but changing the file name solved the problem. Turns out the file name choice caused a redirect to the console, which resulted in the error (must have exactly one of read or write mode): Why does naming a file 'con.txt' in windows make Python write to console, not file?
I need to take lines from a text file and use them as variables in a python function.
def call(file):
with open(file) as infile, open('output.txt', 'w') as outfile:
do stuff in a for loop
file is the variable name and I plan to have a text file containing a list of text file names like so:
hello.txt
world.txt
python.txt
I can call the function with a single file name fine:
call(hello.txt)
But I have a long list of files I need to go through. How can I read the file containing the file names line by line while calling the function once with each file name?
"How can I read the file containing the file names line by line while calling the function once with each file name?" ... you just explained what to do. Supposing your text file containing other filenames is "listoffiles.txt",
with open('listoffiles.txt') as fp:
for line in fp:
filename = line.strip()
if filename:
call(filename)
Note that because call keeps overwriting output.txt you may have other issues.
Depending on other design goals of course, you could have call work on an open file object instead of a file name. This makes the function more generic and potentially useful for other cases such as using other file-like objects such as StringIO.
def call(output, filename):
with open(filename) as infile:
# do some stuff directly with file
with open('output.txt', 'w') as output:
with open('listoffiles.txt') as fp:
for line in fp:
filename = line.strip()
if filename:
call(output, filename)
in the following example I assign a text file string to an arbitrary variable
I then eliminate the '.txt' so as to adhere to variable name convention
then I assign the string value of x to a number 2
x='hello.txt'
x = x.replace(".txt","")
exec("%s = %d" % (x,2))
print(str(x) + ' is equal to: ' + str(hello))
if you try the code you should get
hello is equal to: 2