用python创建一个data.txt,共10行,每行存放一个1-100直接的随机数
时间: 2024-05-05 12:18:58 浏览: 76
可以使用以下Python代码来创建一个data.txt文件,其中包含10行1-100之间的随机数:
```python
import random
# 打开文件
with open('data.txt', 'w') as file:
# 循环10次写入随机数
for i in range(10):
# 生成随机数并转为字符串
rand_num = str(random.randint(1, 100))
# 写入文件并换行
file.write(rand_num + '\n')
```
以上代码将创建一个名为data.txt的文件,并在其中写入10个随机数,每个随机数占一行。每个随机数的范围为1-100之间。请注意,在写入文件时需要使用换行符(\n)将它们分隔开来。
相关问题
用python编写程序创建data.txt,共10行,每行存放1-100之间的随机数,然后读取文本文件,采用readlines方法返回
data.txt 文件的内容。
以下是用 Python 编写程序创建 data.txt 文件的代码:
```python
import random
with open('data.txt', 'w') as f:
for i in range(10):
numbers = [str(random.randint(1, 100)) for _ in range(10)]
f.write(' '.join(numbers) + '\n')
```
以上代码创建了一个名为 data.txt 的文件,并将其写入随机数。现在我们需要读取此文件并返回其内容,我们可以采用 readlines 方法来完成。以下是相应的代码:
```python
with open('data.txt', 'r') as f:
content = f.readlines()
print(content)
```
以上代码将读取 data.txt 文件的内容,并将其存储在名为 content 的变量中。最后一行代码将打印 content 变量的值。
用Python 创建文件data.txt,文件共1000行,每一行存放一个1~50的整数随机数,并读取文章内容。
好的,可以使用Python中的random模块来生成随机数,并使用文件操作函数写入文件和读取文件内容。以下是示例代码:
生成随机数并写入文件:
```python
import random
# 打开文件
with open('data.txt', 'w') as f:
# 生成1000行随机数并写入文件
for i in range(1000):
# 生成1-50的随机数
num = random.randint(1, 50)
# 写入文件
f.write(str(num) + '\n')
```
读取文件内容:
```python
# 打开文件
with open('data.txt', 'r') as f:
# 读取文件内容
content = f.read()
# 输出文件内容
print(content)
```
这样就可以生成一个名为data.txt的文件,并且文件中包含了1000行1-50的随机数。然后通过读取文件内容,可以将文件中的内容输出到控制台。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)