write a one year calendar to file using python - python-2.7

When I run the below code it prints out a calendar for an entire year (which I don't want). I want it to write to file but it won't. It also returns the error message TypeError: expected a character buffer object. Also, casting it into a string doesn't work.
import calendar
cal = calendar.prcal(2015)
with open('yr2015.txt', 'w') as wf:
wf.write(cal)
As an example, the below code prints one month of a year and returns a string, but this isn't what I want
print calendar.month(2015, 4)
print type(calendar.month(2015, 4))
So when I run the below code I get the error message <type 'NoneType'>. It seems to me that it should be a string but obviously isn't. Any suggestions on how I can get a 12-month calendar into a text file?
print type(calendar.prcal(2015))

prcal doesn't return anything. Use cal = calendar.TextCalendar().formatyear(2015) Instead.

Your question is a bit confusing. However, you don't have to make python write to the file.
Let python write to stdout and redirect stdout to a file
python myCal.py > yr2015.txt
This should do the trick

That is because calendar.prcal() will only print the calendar of an year. And it wont return you any values. So this line in your code print type(calendar.prcal(2015)) will return none type error.

Related

NameError: name 'Right' is not defined

I'm trying to execute the following code in Spyder 3.3.1 using Python 2.7.15. I'm a beginner.
text = str(input("You are lost in forest..."))
while text == "Right":
text = str(input("You are lost in forest..."))
print "You got out of the forest!!!"
When I run the code with integer value it works. For example the following piece of code:
text = input("You are lost in forest...")
while text == 1:
text = input("You are lost in forest...")
print "You got out of the forest!!!"
How can I make the input() work with a string value? Thank you for your help.
Use raw_input() instead of input():
value = raw_input("You are lost in forest...") # String input
value = int(raw_input("You are lost in forest...")) # Integer input
...
In python 2, raw_input() takes exactly what the user typed and passes it back as a string. input() tries to understand the data entered by the user.Hence expects a syntactically correct python statement.That's why you got an error when you enter Right. So you can enter "Right" as input to fix this error.
But it is better to use raw_input() instead of input().

Python iterate through txt file of dates and change date format

I have a txt file oldDates.txt. I want to loop through it, modify the date formats and write the newly formatted dates to a new txt file. My code so far:
from datetime import datetime
f = open('oldDates.txt', r)
oldDates = []
newDates = []
for line in f.readlines():
oldDates.append(line)
print(line) # for testing
for oldDate in oldDates:
dt = datetime.strptime(oldDate, '%d/%m/%Y').strftime('%d/%m/%Y')
newDates.append(dt)
with open('newDates.txt', 'w') as w:
for newDate in newDates:
w.write(newDate+"\n")
f.close()
w.close()
However, this give an error:
ValueError: unconverted data remains
I'm not sure where I'm going wrong here, and if there's a more efficient way of doing this then I'd be glad to hear about it. The date conversion seems to work fine from the test print.
There are blank lines in the file and I'm wondering if I need to handle these (I'm not sure how).
Any help much appreciated!
Now, I am no expert in Python, but do you verify your input to be the correct format ? If you apply a regexp on the input line you can easily catch blank lines and any incorrect values.

Python - how do I display an updating value on one line and not scroll down the screen

I have a python script which receives values in real-time. My script prints the values as they are received and currently, each update is printed to the screen and the output scrolls down e.g.
Update 1
Update 2
Update 3
...
Is it possible to have each new value overwrite the previous value on the output screen so that the values don't scroll? e.g.
Update 1
When Update 2 is received the print statement would update the output screen to:
Update 2
and so on...
Thanks in advance for any pointers.
You can pass end='\r' to the print() function. '\r' represents a carriage return in Python. In Python 3 for example:
import time
for i in range(10):
print('Update %d' % i, end='\r')
time.sleep(5)
Here time.sleep(5) is just used to force a delay between prints. Otherwise, even though everything is being printed and then overwritten, it will happen so fast that you will only see the final value 'Update 9'. In your code, it sounds like there is a natural delay while some processes is running, using time.sleep() will not be necessary.
In python 2.7, the print function will not allow an end parameter, and print 'Update %d\r' will also print a newline character.
Here is the same example #elethan gave for python2.7. Note it uses the sys.stdout output stream:
import sys
import time
output_stream = sys.stdout
for i in xrange(10):
output_stream.write('Update %s\r' % i)
output_stream.flush()
time.sleep(5)
# Optionally add a newline if you want to keep the last update.
output_stream.write('\n')
Assuming you have your code which prints the updated list in write_num function,
You can have a function called show_updated_list().
Hoping the clear() every time should resolve this issue:
def show_updated_list():
self.clear()
write_num()

How to Alter returned data format called from csv using python

I am looking for guidance regarding a return result FORMAT from a csv file. The code I have to date partially ahcieves my objective but despite significant effort researching through this and many other sites/forums I cannot resolve the final step. I have also posed this question on gis.stackexchange but was redirected to this forum with the comment "Questions relating to general Information Technology, with no clear GIS component, are off-topic here, but can be researched/asked at Stack Overflow".
My successful piece of python code that reads selected data from a csv and returns it in dict format is below ; (Yes I know the reason it returns as type dict is due to the format my code is calling!!! and that is the crux of the problem)
import arcpy, csv
Att_Dict ={}
with open ("C:/Data/Code/Python/Library/Peter/123.csv") as f:
reader = csv.DictReader(f)
for row in reader:
if row['Status']=='Keep':
Att_Dict.update({row['book_id']:row['book_ref']})
print Att_Dict
Att_Dict = {'7643': '7625', '9644': '2289', '4406': '4443', '7588': '9681', '2252': '7947'}
For the next part of my code to run I need the result above but in the format of ; (this is part of a very lengthy code but the only show stopper is the returned format so little value in posting the other 200 or so lines)
Att_Dict = [[7643, 7625], [9644, 2289], [4406, 4443], [7588, 9681], [2252, 7947]]
Although I have experimented endlessly and can achieve this by reverting to csv.Reader rather than csv.DictReader, I then lose the ability to 'weed out' rows where column 'Status' has value 'Keep' in them and that is a requirement for the task at hand.
My sledgehammer approach to date has been to use 'search and replace' within Idle to amend the returned set to the meet the other requirement but Im sure it can be done programatically rather than manually. Similar but not exact to https://docs.python.org/2/library/index.html, plus my startout question at Returning values from multiple CSV columns to Python dictionary? and Using Python's csv.dictreader to search for specific key to then print its value plus a multitude of csv based questions at geonet.esri.
(Using Win 7, ArcGIS 10.2, Python 2.7.5)
Try this
Att_Dict = {'7643': '7625', '9644': '2289', '4406': '4443', '7588': '9681', '2252': '7947'}
Att_List = []
for key, value in Att_Dict.items():
Att_List.append([int(key), int(value)])
print Att_List
Out: [[7643, 7625], [9644, 2289], [4406, 4443], [7588, 9681], [2252, 7947]]

Print function in python error

I have just started learning python 2.7, and as every new learner i am still getting accustomed to the syntax that python uses. I tried to write this code:
name = raw_input('What is your name?\n')
print 'Hi, %s.' % (name)
I guess the output for the above program should be:
Hi, What is your name?
But i am getting the output as:
What is your name?
After pressing enter key, i get another output:
Hi, .
What is the problem with my code?
There is no problem, it does exactly what you tell it to.
raw_input prints the string argument (as a prompt), and reads input from the user until the first newline, returning the text it has read. This is exactly what happens (try typing some text before hitting Enter). Then the second line takes that text and puts it into the formatting string, printing the result.
The raw_input function is used to take input form the prompt. The string you passed in function will be printed on the prompt followed by your input which gets completed (in sense of python) with the pressing of 'enter key'.
After that the next line print 'Hi, %s.' % (name) will get printed showing the name entered by user in the prompt, which, I assume, is None in your case as you are pressing enter key without any input.