I'm getting an error writing a 'title' line to a csv file:
File ".\aws_ec2_list_instances.py", line 58
title_writer.writerow("AWS Master Instance List " + today)
^
TabError: inconsistent use of tabs and spaces in indentation
I have a variable called today that I want to use:
today = datetime.today()
today = today.strftime("%m-%d-%Y")
This is the line causing the error:
title_writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
title_writer.writerow("AWS Master Instance List " + today)
I want the date as represented by the today variable listed next to the title.
How can I do this correctly?
You can fix this with a Find and Replace operation on your code:
Find: tab '\t'
Replace with: four spaces ' '
Having both tabs and spaces will make python unhappy, pick one and stick with it, I suggest spaces.
In fact, depending on what you are using to write your code, you can have this done automatically if you press tab. In Notepad++ it is under Settings > Preferences > Language > Replace by space
Related
I've written a program using Python 3.10.5 in Visual Studio to read in a block of text from a file and format it as a list. Pretty simple, saves the list to the clipboard so that it can be pasted straight away. Except, when it encounters certain characters in the block of text, errors appear:
a colon (:) causes the program to treat the following lines like a command. The command cannot be understood, so an error occurs.
a less than symbol (<) causes the program to look for a file, declare the file cannot be found, and throw an error.
a more than symbol (>) causes the program to open a new, blank text file, named using the characters that followed the > symbol, and paste the remaining block of text into it.
Why is this happening? And how can I make it stop happening without manually specifying which characters must be ignored or removed from the text before parsing? Code attached below.
import os
def convert_syn_to_list_clip():
out_list = []
with open('syn_list.txt', 'r+', encoding = 'utf-8') as f1:
for line in f1.readlines():
out_list.append(line.rstrip('\n'))
if len(out_list) == 0:
print("EMPTY LIST !!!")
f1.truncate(0)
return str(out_list)
def write_to_clipboard(text):
command = 'echo | set /p nul=' + text.strip() + '| clip'
os.system(command)
write_to_clipboard(convert_syn_to_list_clip())
print("\n\nList in clipboard.\n\n")
I am working with a numpy array in python. I want to print the array and its properties to a txt output. I want the text output to end with a blank line. How can I do this?
I have tried:
# Create a text document of the output
with open("demo_numpy.txt","w") as text:
text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])) + '\n')
And also:
# Create a text document of the output
with open("demo_numpy.txt","w") as text:
text.write('\n'.join(map(str, [a,shape,size,itemsize,ndim,dtype])))
text.write('\n')
However, when I open the file in GitHub desktop, I still get the indication that the last line of the file is "dtype"
When you do "\n".join( ... ) you will get a string of the following form:
abc\ndef\nghi\nhjk
-- in other words, it won't end with \n.
If your code writes another \n then your string will be of the form
abc\ndef\nghi\nhjk\n
But that does not put a blank line at the end of your file because textfiles are supposed to have lines that end in \n. That is what the Posix standard says.
So you need another \n so that the last two lines of your file are
hjk\n
\n
Python will not choke if you ask it to read a textfile where the final trailing \n is missing. But it also won't treat a single trailing \n in a textfile as a blank line. It would not surprise me to learn that GitHub does likewise.
This was solved using the Python 3.x print function, which automatically inserts a new line at the end of each print statement.
Here is the code:
with open("demo_numpy.txt","w") as text:
print(a, file = text)
text.close()
Note- apparently it is more appropriate to use the print function rather than .write when dealing with string values as opposed to binary files.
The section of coding I've written is as such:
thing=9
text_file=open("something.txt", "a")
text_file.write("\n", str(thing))
text_file.close()
This always returns the error Type error: "write" only takes 1 argument. 2 given.
What I'm trying to do is that each time I run this code it writes on a new line rather than the same line. Right now, if this doesn't work, I'm a bit confused how to do this. Any help would be appreciated!
Add a newline to the end1 of the string with the + operator:
text_file.write(str(thing) + "\n")
1Note: If you add it to the front, you will get a blank line at the top of your file, which may not be what you want.
The python interpreter is correct in saying:
"write" only takes 1 argument. 2 given
Python's file methods are documented here.
All you need to be doing is concatenating your string with the newline character. You can do so by replacing:
text_file.write("\n", str(thing))
with:
text_file.write("\n" + str(thing))
This will write an empty line before writing out what you want. This might not be what you are looking for. Instead you can do:
text_file.write(str(thing) + '\n')
I have tried so many options inside csv.reader but its not working. I am new to python and tried almost every parameter,the single messy message inside my csv file look like this
"Hey Hi
how are you all,I stuck into this problem,i have tried with such parameter but exceeding the existing number of records,in short file is not getting read properly.
\"I have tried with
datareader=csv.reader(csvfile,quotechar='"',lineterminator='\n\n\n\r\r',quoting=csv.QUOTE_ALL)
Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode? \"......... hence the problem continue.
"
as expected due to \" and \n in message getting more records or the records getting break,i have tried with different line terminator as well as you can see in the message but not succeed,this is my code right now..
with open("D:/Python/mssg5.csv", "r") as csvfile:
datareader = csv.reader(csvfile,quotechar='"' ,lineterminator='\n',quoting=csv.QUOTE_ALL)
count = 0
#csv_out = open('D:/Python/mycsv.csv', 'wb')
#mywriter = csv.writer(csv_out)
for row in datareader:
count = count + 1
print "COUNT is :%d" % count
Any kind of help,thanks.
A couple of things to try in the csv file:
Put the messy string into tipple quotes """ the string """
At the end of each line within your messy field use the continue char \
My script writes to and creates a new file but it is currently making it in Mac EOL Conversion instead of Windows. This means that each line ends with only 'CR' instead of 'CR LF' which won't work for what i'm trying to do.
Now why this is, or how I can change it?
f = open('...')
text_file1.write(str(i) + ',' + harvestServer + ',' + finalString + harvestCommand + '\r')
text_file1.close()
Replace the \r with \n, having made sure you open the file in text mode. This will use the native convention for your platform (that is, os.linesep).
Alternatively, open the file in binary mode and use \r\n. This will use the Windows convention no matter where you run your code.
Finally, you can control the newline translation by giving the optional newline argument to open().