How to rejoin split words in a file? - python

So far on python I have made a file using the code:
text_file = open("Sentences_Positions.txt", "w")
text_file.write (str(positions))
text_file.write (str(ssplit))
text_file.close()
The code makes the file and writes individual words to it which I previously split, I need to find a way to open the file and join the split words then print it I have tried.
text_file = open("Sentences_Positions.txt", "r")
rejoin = ("Sentences_positions.txt").join('')
print (rejoin)
But all this does is print a blank line in the shell, how should I approach this and what other code could i try?

Read the file content and join them by ''
content = textfile.read().split(' ')
print ''.join(content)

Replace:
rejoin = ("Sentences_positions.txt").join('')
with:
rejoin = ''.join(text_file.read().split(' '))
Also, you should probably not use open but rather the context manager:
with open("Sentences_Positions.txt") as text_file:
rejoin = ''.join(text_file.read().split(' '))
print (rejoin)
Otherwise the file remains open. Using the context manager, it will close it when it's done. (True for the first part of your code as well).

Related

Python reading text files

Please help I need python to compare text line(s) to words like this.
with open('textfile', 'r') as f:
contents = f.readlines()
print(f_contents)
if f_contents=="a":
print("text")
I also would need it to, read a certain line, and compare that line. But when I run this program it does not do anything no error messages, nor does it print text. Also
How do you get python to write in just line 1? When I try to do it for some reason, it combines both words together can someone help thank you!
what is f_contents it's supposed to be just print(contents)after reading in each line and storing it to contents. Hope that helps :)
An example of reading a file content:
with open("criticaldocuments.txt", "r") as f:
for line in f:
print(line)
#prints all the lines in this file
#allows the user to iterate over the file line by line
OR what you want is something like this using readlines():
with open("criticaldocuments.txt", "r") as f:
contents = f.readlines()
#readlines() will store each and every line into var contents
if contents == None:
print("No lines were stored, file execution failed most likely")
elif contents == "Password is Password":
print("We cracked it")
else:
print(contents)
# this returns all the lines if no matches
Note:
contents = f.readlines()
Can be done like this too:
for line in f.readlines():
#this eliminates the ambiguity of what 'contents' is doing
#and you could work through the rest of the code the same way except
#replace the contents with 'line'.

How to print ASCII white space from file

I try to found on google but was useless... I use pycharm and I want to print file lines with ascii white space like "\n", "\t", "\r", etc. but all I get is just the normal string like I see it with any text editor but I want to see and that characters to to know how to reproduce that text file for some personal projects.
I do not what to make them by my self so I want to shoe them on console and to just copy-paste them.
Thanks in advance.
# Local variable
fileName = r"C:\Users\...\textFile.txt"
# Create .mcmeta file
def mcmetaMaker(fileName=fileName):
try:
with open(file=fileName, mode="r", encoding="utf-8") as f:
line = f.readline()
while line:
print("\b{}".format(line))
line = f.readline()
finally:
f.close()
# Local variable
fileName = r"C:\Users\...\textFile.txt"
# Create .mcmeta file
def mcmetaMaker(fileName):
try:
with open(fileName, mode='rb') as f:
line = f.readline()
while line:
betterline = str(line)
print(betterline[2:len(betterline)-1])
line = f.readline()
finally:
f.close()
This worked for me. The 'b' in 'rb' stands for binary mode, which doesn't change the original bytes of the string.
print(line) produces b'asdf\r\n' so I converted it to string and sliced it. Hope it doesn't run too slow this way.

Python writing to file using stdout and fileinput

I have the following code, which modifies each line of the file test.tex by making a regular expression substitution.
import re
import fileinput
regex=re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
for line in fileinput.input('test.tex',inplace=1):
print regex.sub(r'\3\2\1\4\5',line),
The only problem is that I only want the substitution to apply to certain lines in the file, and there's no way to define a pattern to select the correct lines. So, I want to display each line and prompt the user at the command line, asking whether to make the substitution at the current line. If the user enters "y", the substitution is made. If the user simply enters nothing, the substitution is not made.
The problem, of course, is that by using the code inplace=1 I've effectively redirected stdout to the opened file. So there's no way to show output (e.g. asking whether to make the substitution) to the command line that doesn't get sent to the file.
Any ideas?
The file input module is really for dealing with more than one input file.
You can use the regular open() function instead.
Something like this should work.
By reading the file then resetting the pointer with seek(), we can override the file instead of appending to the end, and so edit the file in-place
import re
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
with open('test.tex', 'r+') as f:
old = f.readlines() # Pull the file contents to a list
f.seek(0) # Jump to start, so we overwrite instead of appending
for line in old:
s = raw_input(line)
if s == 'y':
f.write(regex.sub(r'\3\2\1\4\5',line))
else:
f.write(line)
http://docs.python.org/tutorial/inputoutput.html
Based on the help everyone provided, here's what I ended up going with:
#!/usr/bin/python
import re
import sys
import os
# regular expression
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')
# name of input and output files
if len(sys.argv)==1:
print 'No file specified. Exiting.'
sys.exit()
ifilename = sys.argv[1]
ofilename = ifilename+'.MODIFIED'
# read input file
ifile = open(ifilename)
lines = ifile.readlines()
ofile = open(ofilename,'w')
# prompt to make substitutions wherever a regex match occurs
for line in lines:
match = regex.search(line)
if match is not None:
print ''
print '***CANDIDATE FOR SUBSTITUTION***'
print '--: '+line,
print '++: '+regex.sub(r'\3\2\1\4\5',line),
print '********************************'
input = raw_input('Make subsitution (enter y for yes)? ')
if input == 'y':
ofile.write(regex.sub(r'\3\2\1\4\5',line))
else:
ofile.write(line)
else:
ofile.write(line)
# replace original file with modified file
os.remove(ifilename)
os.rename(ofilename, ifilename)
Thanks a lot!

Removing/renaming files in python

I am trying to figure out how I could remove certain words from a file name. So if my file name was lolipop-three-fun-sand,i would input three and fun in and they would get removed. Renaming the file to lolipop--sand. Any ideas on how to start this?
Use string.replace() to remove the words from the filename. Then call os.rename() to perform the rename.
newfilename = filename.replace('three', '').replace('fun', '')
os.rename(filename, newfilename)
import os
line = 'lolipop-three-fun-sand'
delete_list = raw_input("enter ur words to be removed : write them in single quote separated by a comma")
for word in delete_list:
line = line.replace(word, "")
print line

Reading lines including space

I want to read file including spaces in each lines
My current code
def data():
f = open("save.aln")
for line in f.readlines():
print "</br>"
print line
I am using python and output embedded in html
File to be read - http://pastebin.com/EaeKsyvg
Thanks
It seems that your problem is that you need space preserving in HTML. The simple solution would be to put your output between <pre> elemenets
def data():
print "<pre>"
f = open("save.aln")
for line in f.readlines():
print line
print "</pre>"
Note that in this case you don't need the <br> elements either, since the newline characters are also preserved.
The problem that you are faced with is that HTML ignores multiple whitespaces. #itsadok's solution is great. I upvoted it. But, it's not the only way to do this either.
If you want to explicitly turn those whitespaces into HTML whitespace characters, you could to this:
def data():
f = open("save.aln")
for line in f.readlines():
print "<br />"
print line.replace(" ", "&nbsp")
Cheers
import cgi
with open('save.aln') as f:
for line in f:
print cgi.escape(line) # escape <, >, &
print '<br/>'

Categories

Resources