473,698 Members | 2,747 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need to write contents of file to a .txt

Deathwing
32 New Member
Hello,

I'm fairly new to python and have only been playing around with it for one week actually. It's my first attempt at programming and I'm trying to generate some random floats and then have the results of this random generation be filled into a .txt file. So far I have only been able to generate random intergers and create a blank .txt. Can anyone help ? How do I get my ints to turn to floats I have tried using the "float" datatype infront of my numbers but that does not work. Also, how after having generated the random numbers do I get them to populate the .txt file that is created.

Thanks so very much

Here is my code thus far:

# Random number generator
# This script generates random numbers
# The script then writes the result to a text file


text_file = open("points.tx t", "w")
#text_file.writ e(i)

import random

for numbers in range( 1, 201 ):
print "%5d" % ( random.randrang e( 1, 201 ) ),

if numbers % 6 == 0:
print


#text_file.writ elines(numbers)

text_file.close ()

raw_input("\n\n Press the enter key to exit.")
Mar 28 '07 #1
13 2225
bvdet
2,851 Recognized Expert Moderator Specialist
Hello,

I'm fairly new to python and have only been playing around with it for one week actually. It's my first attempt at programming and I'm trying to generate some random floats and then have the results of this random generation be filled into a .txt file. So far I have only been able to generate random intergers and create a blank .txt. Can anyone help ? How do I get my ints to turn to floats I have tried using the "float" datatype infront of my numbers but that does not work. Also, how after having generated the random numbers do I get them to populate the .txt file that is created.

Thanks so very much

Here is my code thus far:

# Random number generator
# This script generates random numbers
# The script then writes the result to a text file


text_file = open("points.tx t", "w")
#text_file.writ e(i)

import random

for numbers in range( 1, 201 ):
print "%5d" % ( random.randrang e( 1, 201 ) ),

if numbers % 6 == 0:
print


#text_file.writ elines(numbers)

text_file.close ()

raw_input("\n\n Press the enter key to exit.")
Maybe you can modify this to meet your requirements:
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. # generate 20 random numbers and write to a text file
  4.  
  5. f = open(r'path\dir\file_name', 'w')
  6. for i in range(20):
  7.     f.write('%.8f\n' % (random.random()))
  8.  
  9. f.close()
  10.  
  11. '''
  12. 0.49790300
  13. 0.22560614
  14. 0.94740230
  15. 0.76629025
  16. 0.54590250
  17. 0.01583565
  18. 0.87463924
  19. 0.39809160
  20. 0.06935606
  21. 0.69546613
  22. 0.79916955
  23. 0.53687077
  24. 0.56587108
  25. 0.78859956
  26. 0.91774516
  27. 0.63878437
  28. 0.38448525
  29. 0.60584063
  30. 0.30951708
  31. 0.56703802
  32. '''
Please use code tags in your posts. See reply guidelines. HTH :)
Mar 28 '07 #2
bvdet
2,851 Recognized Expert Moderator Specialist
Here is another way:
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. f = open(r'path\dir\file_name', 'w')
  4. f.writelines(['%.8f\n' % (random.random()) for _ in range(20)])
  5. f.close()
Mar 28 '07 #3
Deathwing
32 New Member
Thanks bvdet, I'll take a look at it I hope I can modify it, it looks very interesting you have taught me something new todya great! :"D.

Sincerely,

Deathiwng
Mar 28 '07 #4
ghostdog74
511 Recognized Expert Contributor
eg
Expand|Select|Wrap|Line Numbers
  1. python -c "import random; print '\n'.join([str(random.randint(1,201)) for i in range(20)])" > file      
  2.  
Mar 28 '07 #5
Deathwing
32 New Member
eg
Expand|Select|Wrap|Line Numbers
  1. python -c "import random; print '\n'.join([str(random.randint(1,201)) for i in range(20)])" > file      
  2.  
could you explain? I'm sorry I don't understand
Mar 28 '07 #6
Deathwing
32 New Member
Here is another way:
Expand|Select|Wrap|Line Numbers
  1. import random
  2.  
  3. f = open(r'path\dir\file_name', 'w')
  4. f.writelines(['%.8f\n' % (random.random()) for _ in range(20)])
  5. f.close()
Hey bvdet thanks for the tip I have managed to adjust it somewhat but I need to figure out how to get the output/data in to x and y columns here is my modified code. Hope you can help.
Expand|Select|Wrap|Line Numbers
  1. # Random number generator
  2. # This script generates random numbers
  3. # The script then writes the result to a text file
  4. # Guillermo Paniagua - 03/27/07
  5. import random
  6.  
  7.  
  8.  
  9. f = open(r"grapes.txt", "w")
  10. #text_file.write(i)
  11.  
  12.  
  13.  
  14. for i in range( 1, 601 ):
  15.  
  16.  
  17.    f.write( "%5f\n" % ( random.randrange( 1, 601 ) )),
  18.  
  19.   #if numbers % 6 == 0:  
  20.      #print
  21.  
  22.  
  23. #text_file.writelines(numbers)
  24.  
  25. f.close()
  26.  
  27. raw_input("\n\nPress the enter key to exit.")
Mar 28 '07 #7
bvdet
2,851 Recognized Expert Moderator Specialist
Hey bvdet thanks for the tip I have managed to adjust it somewhat but I need to figure out how to get the output/data in to x and y columns here is my modified code. Hope you can help.
Expand|Select|Wrap|Line Numbers
  1. # Random number generator
  2. # This script generates random numbers
  3. # The script then writes the result to a text file
  4. # Guillermo Paniagua - 03/27/07
  5. import random
  6.  
  7.  
  8.  
  9. f = open(r"grapes.txt", "w")
  10. #text_file.write(i)
  11.  
  12.  
  13.  
  14. for i in range( 1, 601 ):
  15.  
  16.  
  17.    f.write( "%5f\n" % ( random.randrange( 1, 601 ) )),
  18.  
  19.   #if numbers % 6 == 0:  
  20.      #print
  21.  
  22.  
  23. #text_file.writelines(numbers)
  24.  
  25. f.close()
  26.  
  27. raw_input("\n\nPress the enter key to exit.")
What do you mean by "get the output/data in to x and y columns"?. Instead of each number on a separate line, do you want the numbers in pairs?
Mar 28 '07 #8
Deathwing
32 New Member
What do you mean by "get the output/data in to x and y columns"?. Instead of each number on a separate line, do you want the numbers in pairs?
hi there and yep an x and y column you are correct I do want numbers in pairs. :)
Mar 28 '07 #9
bartonc
6,596 Recognized Expert Expert
Please read "REPLY GUIDELINES" so that you know how to use CODE tags.
Then start using them. It's a real pain for others to try and see the structure of your code without them.

Thank you very much.
Mar 28 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
2926
by: JDJones | last post by:
I'm trying to write a script that will read from a text list of songs that I burned onto my CD (Albums011.txt), then write to the database text the new text made ready for inserting into a database. The entries from the Albums011.txt look like this: Wayne Newton - Wild Cool & Swingin' - 03 - But Not For Me.mp3 Wayne Newton - Wild Cool & Swingin' - 04 - Wives And Lovers.mp3 etc. and I want to manipulate it them to look in the...
0
1388
by: Joan Bos | last post by:
Hi, Is there somewhere on the Internet a description of what a .NET application config file should contain? For our application, I have to write passwords encrypted in a config file. The Enterprise Library does have an encryption method, but that method doesn't just return a value - no - it wants to write the value immediately to a config file. Except, it always gives an error, because no config file contents are ever good enough for...
1
1842
by: Aalok | last post by:
This is what i want to do. Read a text file as an input and based on that file, Create an outpu text file which saves the contents of the input file in a specifi format in the output file. I know how to read a text file and i can even display the contents o the input file on the prompt. However i am trying to figure out how t save the contents of the input file in a specific manner.
0
1661
by: RSB | last post by:
Hi Every one, i am trying to create a UserControl and i am passing a Array of strings to it. Now based on the Array elements i am creating the LinkButtons Dynamically. I am also passing a Event to this control and Lining the OnClick event of these LinkButtons to this Event. (Which works fine). Now the Thing which i cannot achieve is i want to Change the Back Color of the Clicked to LinkButton To a different color and i also don't want to...
15
3649
by: Gan Quan | last post by:
I'm writing a c++ program that has many (100+) threads read/write files simultaneously. It works well if not considering the efficiency. The file i/o seems to be the bottleneck. This is my code to read from and write to files: #include <fstream> #include <sstream> #include <string>
2
2590
kamill
by: kamill | last post by:
i need to write content of one text file into another text file. My code is working ,if i choose both files from same directory where my program reside..BUT,its not working if i select files from out of that directory(where my application reside). how can i overcome to it. my code is this.. Form to select two files <form method="post" action="" enctype="multipart/form-data">
24
4438
by: Bill | last post by:
Hello, I'm trying to output buffer content to a file. I either get an access violation error, or crazy looking output in the file depending on which method I use to write the file. Can anyone help out a newbie? #include <stdio.h> #include <ctype.h> #include <string.h>
4
1573
by: Paul David Buchan | last post by:
Hello, I'm attempting to write a program to read in database files (.dbf). When I do it all as a single procedure in main, everything works. However, what I really want, is to pass the database filename to a function, and have it pass back an array containing the database contents, and some parameters telling me the dimensions of the array. I've succeeded in getting my function to read in the dbf file, and it returns the dimensions of...
11
4356
by: blunt | last post by:
trying to write a program to write the configuration files for a load of wireless access points. i've never been a good programmer and haven't done any for nearly a decade so have obviously made some mistakes, i'm using cygwin on a windows pc and it seems that some functions cause stack overflows so am using fgets instead of fgetc (don't know y it solved the problem but that part is working). my problem now is that i am reading strings a few...
0
8683
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9031
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7741
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5867
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.