Python 如何创建大小为N KB、重复次数为“的文本文件”;“你好,世界”;

Python 如何创建大小为N KB、重复次数为“的文本文件”;“你好,世界”;,python,Python,我想在python的帮助下,创建一个大小为N KB的文本文件,重复“Hello World”,其中N是通过存储库中不同目录中的配置文件指定的。我能够多次显示hello world N,其中N是来自配置文件的数字输入,但我对大小一无所知。以下是我迄今为止编写的代码: import ConfigParser import webbrowser configParser = ConfigParser.RawConfigParser() configParser.read("/home/suryavee

我想在python的帮助下,创建一个大小为N KB的文本文件,重复“Hello World”,其中N是通过存储库中不同目录中的配置文件指定的。我能够多次显示hello world N,其中N是来自配置文件的数字输入,但我对大小一无所知。以下是我迄今为止编写的代码:

import ConfigParser
import webbrowser
configParser = ConfigParser.RawConfigParser()
configParser.read("/home/suryaveer/check.conf")
num = configParser.get('userinput-config', 'num')
num2 = int(num)
message = "hello world"
f = open('test.txt', 'w')
f.write(message*num2)
f.close()

首先,您必须弄清楚写入的字符数和字节数之间的区别。在许多编码中,一个字符占1个字节以上。在您的示例中,如果短语为英语(“Hello world”),默认编码为
utf-8
,则数字将是相同的,但如果您使用不同的字符集启用其他语言,则数字可能会有所不同

...
with open('test.txt', 'wb') as f:  # binary because we need count bytes
  max_size = num2 * 1024  # I assume num2 in kb
  msg_bytes = message.encode('utf-8')
  bytes_written = 0
  while bytes_written < max_size:  # if you dont need breaking the last phrase
    f.write(msg_bytes) 
    bytes_written += len(msg_bytes)
。。。
使用open('test.txt','wb')作为f:#二进制,因为我们需要计算字节数
max_size=num2*1024#我假设num2以kb为单位
msg_bytes=message.encode('utf-8')
写入的字节数=0
而bytes_write
长度为1的字符串是1字节(只要它是utf8)。 这意味着“Hello World”的大小(以字节为单位)是
len(“Hello World”)
=11字节

要获得~N千字节,可以运行以下操作:

# N is int
size_bytes = N * 1024
message = "hello world"
# using context manager, so no need to remember to close the file.
with open('test.txt', 'w') as f:
  repeat_amount = int((size_bytes/len(message))
  f.write(message * repeat_amount)

首先获取
消息的大小,记住Pyhton中的字符串是对象,因此当调用
sys.getsizeof(message)
时,这不是纯字符串,而是对象本身。然后,只需计算重复纯
消息
以获得
N
Kb所需的时间,如下所示:

import sys

N = 1024 # size of the output file in Kb
message = "hello world"

string_object_size = sys.getsizeof("")
single_message_size = sys.getsizeof(message) - string_object_size

reps = int((N)*1024/single_message_size)

f = open('test.txt', 'w')
f.write(message*reps)
f.close() 

注意:test.txt将包含1行,大小为N KB。如果需要
重复\u行数
可以添加'\n',只需在@kerbelp所说的内容后面加一个注释,
\n
在Python(UTF-8)中占用2个字节,因此您可能会发现这两个文件中的
hello world
的迭代中存在巨大差异(尽管绝对文件大小将保持不变),我确实想知道您为什么要这样做。你到底想做什么?你好,jorijnsmit,这是我作业的一部分,我正在努力完成它,因为我是编程新手,所以我想得到解决方案的清晰解释:-)