I'm trying to open a file, and edit a specific line. When I concatenate a character onto one of the lines, it works, but inserts a new line. However I don't want a new line. Here is the code:
def moveCurlyInline(line, i):
with open('test.js', 'r') as inputFile:
data = inputFile.readlines()
print(data[0])
print(data[0] + ' {')
The print outputs:
function hello()
then:
function hello()
{
I need the curly bracket to be on the same line as the function hello. Any idea what's wrong with my code?
f.readline() reads a line from the file, including the newline at the end of the line.
Try stripping the extra newline:
data = [line.rstrip("\n") for line in inputFile]
You can strip new line character by
inputFile.read().striplines()
Related
I'm trying to write encoded data to a file and separate each run with a newline character. However, when doing this there is an empty line between each run -- as shown below.
Using .rstrip()/.strip() only really works when reading the file -- and obviously this cannot be used directly when writing to the file as it would write all the data to a single line.
cFile = open('compFile', 'w')
for i in range(num_lines):
line = validLine()
compressedFile.write(line + "\n")
cFile.close()
cFile = open('compFile', 'r')
for line in cFile:
print(line)
# Empty space output:
023
034
045
# Desired output:
023
034
045
I think you already did what you want if you have a look at your text file.
Be aware, that python reads the \n at the end of your file too and that print() makes a newline at the end of the printed line.
In your case that means your file should look like
023\n
034\n
045\n
When printing, you at first read 023\n and then as python does with the print() function you append a \n to your line.
Then you have the 023\n\n you get in your console. But in the file you have what you want.
If you just want to print without linebreak, you can use
import sys
sys.stdout.write('.')
You could use
for i in range(num_lines):
line = validLine()
compressedFile.write(line.strip() + "\n")
# ^^^
cFile.close()
Off-topic but consider using with () additionally.
Using .rstrip()/.strip() only really works when reading the file -- and obviously this cannot be used directly when writing to the file as it would write all the data to a single line.
This is a misconception. Using .rstrip() is exactly the correct tool if you need to write a series of strings, some of which may have a newline character attached:
with open('compFile', 'w') as cFile:
for i in range(num_lines):
line = validLine().rstrip("\n") # remove possible newline
compressedFile.write(line + "\n")
Note that if all your lines already have a newline attached, you don't have to add more newlines. Just write the string directly to the file, no stripping needed:
with open('compFile', 'w') as cFile:
for i in range(num_lines):
line = validLine() # line with "\n" newline already present
compressedFile.write(line) # no need to add a newline anymore
Next, you are reading lines with newlines from your file and then printing them with print(). By default, print() adds another newline, so you end up with double-spaced lines; your input file contains 023\n034\n045\n, but printing each line ('023\n', then '034\n', then '045\n') adds a newline afterwards and you write out 023\n\n034\n\n045\n\n out to stdout.
Either strip that newline when printing, or tell print() to not add a newline of its own by giving it an empty end parameter:
with open('compFile', 'r') as cFile:
for line in cFile:
print(line, end='')
I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.
I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.
# Example of what I did
with open('MyFile.m') as f:
for line in f:
text = f.readline()
if text.startswith('%'):
continue
else:
my_string = text.strip("=")
my_list.append(my_string)
This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e S t r i n g"
Without your input file I've had to make some guesses here
Input file:
%
The
%
String
%
Solution:
my_list = []
with open('MyFile.m') as f:
for line in f:
if not line.startswith('%'):
my_list.append(line.strip("=").strip())
print(' '.join(my_list))
The readLine() call was unnecessary as the for loop already gets you the line. The empty if was negated to only catch the part that you cared about. Without your actual input file I can't help with the '=' part. If you have any clarifications I'd be glad to help further.
As suggested by Xander, you shouldn't call readline since the for line in f does that for you.
my_list = []
with open('MyFile.m') as f:
for line in f:
line = line.strip() # lose the \n if you want to
if line.startswith('%'):
continue
else:
my_string = line.strip("=")
my_list.append(my_string)
I am reading from an external text file, named 'greeting.txt' where the contents of the text file are simply:
HELLO
However, when I attempt to print the contents of the text file enclosed in quotes the terminal prints out:
"HELLO
"
I am using the following code:
for line in open('greeting.txt', "r"): print ('"%s"' % line)
I desire the string to be enclosed in quotes printed on the same line.
I have never encountered this problem before despite using Python for similar purposes, any help would be appreciated.
There is a end of line character in your text file after Hello. That end of line is also getting enclosed in the double quotes and causing the second quote to get printed on the second line. You should strip the end of line using rstrip()
for line in open('greeting.txt', "r"): print ('"%s"' % line.rstrip())
The problem is that, what is written in your file is probably Hello\n and if you read the whole line you are then printing "Hello\n" which causes the newline to be in front of the second quote. Use the strip() method to get rid of any trailing whitespaces like so:
for line in open('greeting.txt', "r"): print ('"%s"' % line.strip())
However I would suggest changing your code to:
with open('greeting.txt', "r") as f:
for line in f: print ('"%s"' % line.strip())
Since I personally do not like to have open without making sure, that the file is being closed as soon as I am done with it.
You can strip the trailing whitespaces using the rstrip() function.
for line in open('greeting.txt', "r"): print ('"%s"' % line.rstrip())
I am trying to do a simple parsing on a text in python which I have no issues with in bash using tr '\n' ' '. Basically to get all of the lines on a single line. In python print line is a bit different from what I understand. re.sub cannot find my new line because it doesn't exist even though when I print to an output it does. Can someone explain how I can work around this issue in python?
Here is my code so far:
# -*- iso-8859-1 -*-
import re
def proc():
f= open('out.txt', 'r')
lines=f.readlines()
for line in lines:
line = line.strip()
if '[' in line:
line_1 = line
line_1_split = line_1.split(' ')[0]
line_2 = re.sub(r'\n',r' ', line_1_split)
print line_2
proc()
Edit: I know that "print line," will print without the newline. The issue is that I need to handle these lines both before and after doing operations line by line. My code in shell uses sed, awk and tr to do this.
You can write directly to stdout to avoid the automatic newline of print:
from sys import stdout
stdout.write("foo")
stdout.write("bar\n")
This will print foobar on a single line.
When you call the print statement, you automatically add a new line. Just add a comma:
print line_2,
And it will all print on the same line.
Mind you, if you're trying to get all lines of a file, and print them on a single line, there are more efficient ways to do this:
with open('out.txt', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
# Some extra line formatting stuff goes here
print line, # Note the comma!
Alternatively, just join the lines on a string:
everything_on_one_line = ''.join(i.strip() for i in f.readlines())
print everything_on_one_line
Using with ensures you close the file after iteration.
Iterating saves memory and doesn't load the entire file.
rstrip() removes the newline in the end.
Combined:
with open('out.txt', 'r') as f:
for line in f:
print line.rstrip(),
Use replace() method.
file = open('out.txt', 'r')
data = file.read()
file.close()
data.replace('\n', '')
I am new to python. I have a document that has one random word per line. There are thousands of words in this file. I am trying to print only the words that are four letters long. I tried this:
f=open("filename.txt")
Words=f.readlines()
for line in f:
if len(line)==4:
print(line)
f.close()
But python is blank when I do this. I am assuming I need to strip the blank spaces as well, but when I did
f.strip()
I received an error stating that .strip() doesn't apply to list items. Any help is grateful. Thanks!
'Python is blank' because you attempt to iterate over the file for a second time.
The first time is with readlines(), so when that iteration is finished you are at the end of the file. Then when you do for line in f you are already at the end of the file so there is nothing left over which to iterate. To fix this, drop the call to readlines().
To do what you want to have, I would just do this:
with open('filename.txt') as f:
for line in f: # No need for `readlines()`
word = line.strip() # Strip the line, not the file object.
if len(word) == 4:
print(word)
Your other error occurs with f.strip() because f is a file object- but you only strip a string. Therefore just split the line on each iteration as shown in the example above.
You should do:
for line in Words:
instead of
for line in f:
You want line.strip() because f is a file object, not a string.