I'm trying to open .txt file and am getting confused with which part goes where. I also want that when I open the text file in python, the spaces removed.And when answering could you make the file name 'clues'.
My first try is:
def clues():
file = open("clues.txt", "r+")
for line in file:
string = ("clues.txt")
print (string)
my second try is:
def clues():
f = open('clues.txt')
lines = [line.strip('\n') for line in open ('clues.txt')]
The thrid try is:
def clues():
f = open("clues.txt", "r")
print f.read()
f.close()
Building upon #JonKiparsky It would be safer for you to use the python with statement:
with open("clues.txt") as f:
f.read().replace(" ", "")
If you want to read the whole file with the spaces removed, f.read() is on the right track—unlike your other attempts, that gives you the whole file as a single string, not one line at a time. But you still need to replace the spaces. Which you need to do explicitly. For example:
f.read().replace(' ', '')
Or, if you want to replace all whitespace, not just spaces:
''.join(f.read().split())
This line:
f = open("clues.txt")
will open the file - that is, it returns a filehandle that you can read from
This line:
open("clues.txt").read().replace(" ", "")
will open the file and return its contents, with all spaces removed.
Related
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 have a text file that looks like this:
1,004,59
1,004,65
1,004,69
1,005,55
1,005,57
1,006,53
1,006,59
1,007,65
1,007,69
1,007,55
1,007,57
1,008,53
Want to create new text file that will be inserted by 'input', something like this
1,004,59,input
1,004,65,input
1,004,69,input
1,005,55,input
1,005,57,input
1,006,53,input
1,006,59,input
1,007,65,input
1,007,69,input
1,007,55,input
1,007,57,input
1,008,53,input
I have attempted something like this:
with open('data.txt', 'a') as f:
lines = f.readlines()
for i, line in enumerate(lines):
line[i] = line[i].strip() + 'input'
for line in lines:
f.writelines(line)
Not able to get the right approach though.
What you want is to be able to read and write to the file in place (at the same time). Python comes with the fileinput module which is good for this purpose:
import fileinput
for line in fileinput.input('data.txt', inplace=True):
line = line.rstrip()
print line + ",input"
Discusssion
The fileinput.input() function returns a generator that reads your file line by line. Each line ends up with a new line (either \n or \r\n, depends on the operating system).
The code then strip off each line of this new line, add the ",input" part, then print out. Note that because of fileinput magic, the print statement's output will go back into the file instead of the console.
There are a newline '\n' in every line in your file, so you should handle it.
edit: oh I forgot about the rstrip() function!
tmp = []
with open("input.txt", 'r') as file:
appendtext = ",input\n"
for line in file:
tmp.append(line.rstrip() + appendtext)
with open("input.txt", 'w') as file:
file.writelines(tmp)
Added:
Answer by Hai_Vu is great if you use fileinput since you don't have to open the file twice as I did.
To do only the thing you're asking I would go for something like
newLines = list()
with open('data.txt', 'r') as f:
lines = f.readlines()
for line in lines:
newLines.append(line.strip() + ',input\n')
with open('data2.txt', 'w') as f2:
f2.writelines(newLines)
But there are definitely more elegant solutions
I was wondering how to make a .text file so I can put words in it and then in my program open the file. I just need to know how to make a .text file!
Anyone know why my code won't open my .txt file when I try to run it?
def readWords(filename):
words = []
wordFile = open(words.txt, "r")
for line in wordFile:
line = line.upper()
words.extend(string.split(line))
wordFile.close()
return words
with open('myfile.txt', 'w') as f:
f.write('potato')
Opening a file in write mode will create it for you if it doesn't already exist:
with open("/path/to/file.txt", "w") as myfile:
# Do whatever
In the above code, myfile will be the file object.
Here is a reference on open and one on with.
Instead on reading each and every line cant we just search for the string in the file and replace it... i am trying but unable to get any idea how to do thth?
file = open(C:\\path.txt,"r+")
lines = file.readlines()
replaceDone=0
file.seek(0)
newString="set:: windows32\n"
for l in lines:
if (re.search("(address_num)",l,re.I) replaceDone==0:
try:
file.write(l.replace(l,newString))
replaceDone=1
except IOError:
file.close()
Here's an example you can adapt that replaces every sequence of '(address_num)' with 'set:: windows32' for a file:
import fileinput
import re
for line in fileinput.input('/home/jon/data.txt', inplace=True):
print re.sub('address_num', 'set:: windows32', line, flags=re.I),
This is not very memory efficient but I guess it is what you are looking for:
import re
text = open(file_path, 'r').read()
open(file_path, 'w').write(re.sub(old_string, new_string, text))
Read the whole file, replace and write back the whole file.
I have a txt file with list of html/doc files, I want to download them using python and save them as 1.html, 2.doc, 3.doc, ...
http://example.com/kran.doc
http://example.com/loj.doc
http://example.com/sks.html
I've managed to create fully functional script except python will allways add question mark to the end of newly created file (if you look from linux) and if you look from windows file name would be something like 5CFB43~X
import urllib2
st = 1;
for line in open('links.txt', 'r'):
u = urllib2.urlopen(line)
ext = line.split(".")
imagefile = str(st)+"."+ext[-1]
#file created should be something.doc but its something.doc? -> notice question mark
fajl = open(imagefile, "w+")
fajl.write(u.read())
fajl.close()
print imagefile
st += 1
The line terminator is two characters, not one.
for line in open('links.txt', 'rU'):
But not anymore.
Work on line.strip() instead of line
That's because lines read this way will end up with '\n' at the end, hence the ?
Just add the following at the beginning of your loop:
if line.endswith('\n'):
line = line[:-1]
Or as AKX pointed out in the comments, just:
line = line.rstrip('\r\n')
And so you cover any kind of line ending.